
package com.shop.cloud.controller.hongfu;


import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;

import com.google.zxing.WriterException;
import com.shop.cloud.Shift;
import com.shop.cloud.StatusCode;
import com.shop.cloud.JPush.MsgPushUtils;
import com.shop.cloud.auth0.jwt.Token;
import com.shop.cloud.auth0.jwt.TokenGenerator;
import com.shop.cloud.auth0.jwt.exceptions.JWTCreationException;
import com.shop.cloud.common.mapper.JsonMapper;
import com.shop.cloud.common.token.UserTokenGenerator;
import com.shop.cloud.controller.hongfu.httputil.HttpClientUtil;
import com.shop.cloud.dao.hongfu.GoodsDao;
import com.shop.cloud.dao.hongfu.UserDao;
import com.shop.cloud.domain.hongfu.Activity;
import com.shop.cloud.domain.hongfu.ActivityEnroll;
import com.shop.cloud.domain.hongfu.Area;
import com.shop.cloud.domain.hongfu.BalanceHistory;
import com.shop.cloud.domain.hongfu.Banner;
import com.shop.cloud.domain.hongfu.City;
import com.shop.cloud.domain.hongfu.Code;
import com.shop.cloud.domain.hongfu.Goods;
import com.shop.cloud.domain.hongfu.GoodsCategory;
import com.shop.cloud.domain.hongfu.GoodsCategoryFeature;
import com.shop.cloud.domain.hongfu.GoodsCategoryFeatureValue;
import com.shop.cloud.domain.hongfu.GoodsCategoryProperty;
import com.shop.cloud.domain.hongfu.GoodsFeature;
import com.shop.cloud.domain.hongfu.GoodsFeatureImage;
import com.shop.cloud.domain.hongfu.GoodsImage;
import com.shop.cloud.domain.hongfu.GoodsInventory;
import com.shop.cloud.domain.hongfu.GoodsOrder;
import com.shop.cloud.domain.hongfu.GoodsOrderFeature;
import com.shop.cloud.domain.hongfu.GoodsProperty;
import com.shop.cloud.domain.hongfu.InviteConfig;
import com.shop.cloud.domain.hongfu.InviteHistory;
import com.shop.cloud.domain.hongfu.Message;
import com.shop.cloud.domain.hongfu.News;
import com.shop.cloud.domain.hongfu.Notice;
import com.shop.cloud.domain.hongfu.PointsHistory;
import com.shop.cloud.domain.hongfu.Province;
import com.shop.cloud.domain.hongfu.Region;
import com.shop.cloud.domain.hongfu.Shop;
import com.shop.cloud.domain.hongfu.ShopAptitude;
import com.shop.cloud.domain.hongfu.ShopImage;
import com.shop.cloud.domain.hongfu.ShopReport;
import com.shop.cloud.domain.hongfu.ShopType;
import com.shop.cloud.domain.hongfu.SignHistory;
import com.shop.cloud.domain.hongfu.SysConfig;
import com.shop.cloud.domain.hongfu.SysEdition;
import com.shop.cloud.domain.hongfu.Tag;
import com.shop.cloud.domain.hongfu.User;
import com.shop.cloud.domain.hongfu.UserAddress;
import com.shop.cloud.domain.hongfu.UserConfig;
import com.shop.cloud.domain.hongfu.UserLevel;
import com.shop.cloud.domain.hongfu.UserLoginHistory;
import com.shop.cloud.domain.hongfu.WithdrawHistory;
import com.shop.cloud.filter.CurrentUserId;
import com.shop.cloud.filter.IgnoreAuth;
import com.shop.cloud.model.request.api.ApiAddAddressRequest;
import com.shop.cloud.model.request.api.ApiAddressHandleRequest;
import com.shop.cloud.model.request.api.ApiBindPhoneRequest;
import com.shop.cloud.model.request.api.ApiChangePwdRequest;
import com.shop.cloud.model.request.api.ApiDelMessageRequest;
import com.shop.cloud.model.request.api.ApiForgetPwdRequest;
import com.shop.cloud.model.request.api.ApiGetActivityDetailRequest;
import com.shop.cloud.model.request.api.ApiGetActivityListRequest;
import com.shop.cloud.model.request.api.ApiGetAddressListRequest;
import com.shop.cloud.model.request.api.ApiGetAreaRequest;
import com.shop.cloud.model.request.api.ApiGetBalanceDetailListRequest;
import com.shop.cloud.model.request.api.ApiGetCodeRequest;
import com.shop.cloud.model.request.api.ApiGetConfigRequest;
import com.shop.cloud.model.request.api.ApiGetConfigRequestModel;
import com.shop.cloud.model.request.api.ApiGetDefaultAddressRequest;
import com.shop.cloud.model.request.api.ApiGetGoodsDetailByFeatureRequest;
import com.shop.cloud.model.request.api.ApiGetGoodsDetailRequest;
import com.shop.cloud.model.request.api.ApiGetGoodsListRequest;
import com.shop.cloud.model.request.api.ApiGetGoodsOrderDetailRequest;
import com.shop.cloud.model.request.api.ApiGetGoodsOrderListRequest;
import com.shop.cloud.model.request.api.ApiGetGoodsOrderOperationRequest;
import com.shop.cloud.model.request.api.ApiGetGoodsOrderRequest;
import com.shop.cloud.model.request.api.ApiGetGoodsTypeRequest;
import com.shop.cloud.model.request.api.ApiGetHomeInfoRequest;
import com.shop.cloud.model.request.api.ApiGetIntegralDetailListRequest;
import com.shop.cloud.model.request.api.ApiGetInviteInfoRequest;
import com.shop.cloud.model.request.api.ApiGetMessageListRequest;
import com.shop.cloud.model.request.api.ApiGetMyActivityListRequest;
import com.shop.cloud.model.request.api.ApiGetMyIntegralRequest;
import com.shop.cloud.model.request.api.ApiGetMyShopDetailRequest;
import com.shop.cloud.model.request.api.ApiGetNewsDetailRequest;
import com.shop.cloud.model.request.api.ApiGetNewsListRequest;
import com.shop.cloud.model.request.api.ApiGetSelfSupportListRequest;
import com.shop.cloud.model.request.api.ApiGetShopDetailRequest;
import com.shop.cloud.model.request.api.ApiGetShopListRequest;
import com.shop.cloud.model.request.api.ApiGetShopTypeRequest;
import com.shop.cloud.model.request.api.ApiGetSysMsgListRequest;
import com.shop.cloud.model.request.api.ApiGetTourListRequest;
import com.shop.cloud.model.request.api.ApiGetTourTypeRequest;
import com.shop.cloud.model.request.api.ApiGetUserInfoRequest;
import com.shop.cloud.model.request.api.ApiGetWithdrawListRequest;
import com.shop.cloud.model.request.api.ApiJoinRequest;
import com.shop.cloud.model.request.api.ApiLoginRequest;
import com.shop.cloud.model.request.api.ApiRechargeOrderRequest;
import com.shop.cloud.model.request.api.ApiRechargePayRequest;
import com.shop.cloud.model.request.api.ApiRegisterRequest;
import com.shop.cloud.model.request.api.ApiReportShopRequest;
import com.shop.cloud.model.request.api.ApiSearchRequest;
import com.shop.cloud.model.request.api.ApiSignRequest;
import com.shop.cloud.model.request.api.ApiThirdPartyLoginRequest;
import com.shop.cloud.model.request.api.ApiUpdateUserInfoRequest;
import com.shop.cloud.model.response.ObjectDataResponse;
import com.shop.cloud.model.response.api.*;
import com.shop.cloud.security.EncodeUtil;
import com.shop.cloud.service.hongfu.IDistributionMsgService;
import com.shop.cloud.service.hongfu.ISysEditionService;
import com.shop.cloud.service.hongfu.ITagService;
import com.shop.cloud.service.hongfu.impl.ActivityEnrollService;
import com.shop.cloud.service.hongfu.impl.ActivityService;
import com.shop.cloud.service.hongfu.impl.AdvService;
import com.shop.cloud.service.hongfu.impl.BalanceHistoryService;
import com.shop.cloud.service.hongfu.impl.BannerService;
import com.shop.cloud.service.hongfu.impl.CityService;
import com.shop.cloud.service.hongfu.impl.CodeService;
import com.shop.cloud.service.hongfu.impl.GoodsCategoryFeatureService;
import com.shop.cloud.service.hongfu.impl.GoodsCategoryFeatureValueService;
import com.shop.cloud.service.hongfu.impl.GoodsCategoryPropertyService;
import com.shop.cloud.service.hongfu.impl.GoodsCategoryService;
import com.shop.cloud.service.hongfu.impl.GoodsFeatureImageService;
import com.shop.cloud.service.hongfu.impl.GoodsFeatureService;
import com.shop.cloud.service.hongfu.impl.GoodsImageService;
import com.shop.cloud.service.hongfu.impl.GoodsInventoryService;
import com.shop.cloud.service.hongfu.impl.GoodsOrderFeatureService;
import com.shop.cloud.service.hongfu.impl.GoodsOrderService;
import com.shop.cloud.service.hongfu.impl.GoodsPropertyService;
import com.shop.cloud.service.hongfu.impl.GoodsService;
import com.shop.cloud.service.hongfu.impl.InviteConfigService;
import com.shop.cloud.service.hongfu.impl.InviteHistoryService;
import com.shop.cloud.service.hongfu.impl.MessageService;
import com.shop.cloud.service.hongfu.impl.NewsService;
import com.shop.cloud.service.hongfu.impl.NoticeService;
import com.shop.cloud.service.hongfu.impl.PointsHistoryService;
import com.shop.cloud.service.hongfu.impl.ProvinceService;
import com.shop.cloud.service.hongfu.impl.RegionService;
import com.shop.cloud.service.hongfu.impl.ShopAptitudeService;
import com.shop.cloud.service.hongfu.impl.ShopImageService;
import com.shop.cloud.service.hongfu.impl.ShopReportService;
import com.shop.cloud.service.hongfu.impl.ShopService;
import com.shop.cloud.service.hongfu.impl.ShopTypeService;
import com.shop.cloud.service.hongfu.impl.SignHistoryService;
import com.shop.cloud.service.hongfu.impl.SysConfigService;
import com.shop.cloud.service.hongfu.impl.TravelTypeService;
import com.shop.cloud.service.hongfu.impl.UserAddressService;
import com.shop.cloud.service.hongfu.impl.UserConfigService;
import com.shop.cloud.service.hongfu.impl.UserLevelService;
import com.shop.cloud.service.hongfu.impl.UserLoginHistoryService;
import com.shop.cloud.service.hongfu.impl.UserService;
import com.shop.cloud.service.hongfu.impl.WithdrawHistoryService;
import com.shop.cloud.util.CookieManager;
import com.shop.cloud.util.MagicConstants;
import com.shop.cloud.util.StringUtils;

/**
 * api
 */
@RestController	
@RequestMapping("api")
public class ApiController {
	
	@Autowired
	private GoodsDao goodsdao;
	
	@Autowired
	private UserLevelService userLevelService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private SysConfigService sysConfigService;
	
	@Autowired
	private PointsHistoryService pointsHistoryService;
	
	@Autowired
	private InviteHistoryService inviteHistoryService;
	
	@Autowired
	private UserConfigService userConfigService;
	
	@Autowired
	private UserLoginHistoryService userLoginHistoryService;
	
	@Autowired
	private CodeService codeService;
	
	@Autowired
	private ProvinceService provinceService;
	
	@Autowired
	private CityService cityService;
	
	@Autowired
	private RegionService regionService;
	
	@Autowired
	private ShopService shopService;
	
	@Autowired
	private AdvService advService;
	
	@Autowired
	private BannerService bannerService;
	
	@Autowired
	private NoticeService noticeService;
	
	@Autowired
	private NewsService newsService;
	
	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private GoodsImageService goodsImageService;
	
	@Autowired
	private GoodsCategoryService goodsCategoryService;
	
	@Autowired
	private GoodsPropertyService goodsPropertyService;
	
	@Autowired
	private GoodsCategoryPropertyService goodsCategoryPropertyService;
	
	@Autowired
	private GoodsFeatureService goodsFeatureService;
	
	@Autowired
	private GoodsCategoryFeatureService goodsCategoryFeatureService;
	
	@Autowired
	private GoodsCategoryFeatureValueService goodsCategoryFeatureValueService;
	
	@Autowired
	private GoodsInventoryService goodsInventoryService;
	
	@Autowired
	private GoodsFeatureImageService goodsFeatureImageService;
	
	@Autowired
	private TravelTypeService travelTypeService;
	
	@Autowired
	private ActivityService activityService;
	
	@Autowired
	private ActivityEnrollService activityEnrollService;
	
	@Autowired
	private ShopTypeService shopTypeService;
	
	@Autowired
	private ShopAptitudeService shopAptitudeService;
	
	@Autowired
	private ShopImageService shopImageService;
	
	@Autowired
	private ShopReportService shopReportService;
	
	@Autowired
	private GoodsOrderService goodsOrderService;
	
	@Autowired
	private BalanceHistoryService balanceHistoryService;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private WithdrawHistoryService withdrawHistoryService;
	
	@Autowired
	private UserAddressService userAddressService;
	
	@Autowired
	private SignHistoryService signHistoryService;
    
	@Autowired
	private GoodsOrderFeatureService goodsOrderFeatureService;
	
	@Autowired
	private InviteConfigService inviteConfigService;
	
	@Autowired
	private ISysEditionService sysEditionService;
	
	@Autowired
	private IDistributionMsgService distributionMsgService;
	
	@Autowired
	private ITagService tagService;
	
	@Autowired
	private UserDao userDao;
	
	private static final String MESSAGE_URL = "http://106.wx96.com/webservice/sms.php?method=Submit";//短信验证码URL
	private static final String MESSAGE_APIID = "C80020729";//短信验证码 APIID
	private static final String MESSAGE_PASSWORD = "cbcca6677810b864d237e80d03e29518";//短信验证码 密码
	private static int CONTENT_CODE = 0;//短信验证码
	Logger logger = Logger.getLogger(ApiController.class);
	
	
	
//	    @IgnoreAuth
//	    @ApiOperation(value = "H5获取用户信息" , notes="H5获取用户信息")
//		@RequestMapping(value = "getGMC", method = RequestMethod.GET)
//		@ResponseBody
//		public Response getUserId(Long userId){
//	    	
//	    	User userEntity = userService.get(userId);	
//	    	User user = new User();
//	    	user.setNickname(userEntity.getNickname());
//	    	user.setPortrait(user.getPortrait());
//	    	Map<String, Object> params = new HashMap<String, Object>();
//	    	params.put("user", user);
//	    	
//	    	return ResponseUtil.ok(params);
//
//		}
	
    @IgnoreAuth
    @ApiOperation(value = "H5获取用户信息" , notes="H5获取用户信息")
	@RequestMapping(value = "getUserId", method = RequestMethod.GET)
	@ResponseBody
	public ObjectDataResponse<User> getUserId(int userId){
		
    	User userEntity = userService.get((long)userId);	
    	User user = new User();
    	if(userEntity.getNickname() !=null){
    		
    		user.setNickname(userEntity.getNickname());
    	}
    	if(userEntity.getPortrait() !=null){
    	user.setPortrait(userEntity.getPortrait());
    	}
		return new ObjectDataResponse<User>(user);
	}
	
	
	
	@IgnoreAuth
	@ApiOperation(value = "查询最新版本号" , notes="查询最新版本号")
	@RequestMapping(value = "queryEditionOne", method = {RequestMethod.POST,RequestMethod.GET}  )
	@ResponseBody
	public ObjectDataResponse<SysEdition> queryEditionOne(@RequestBody SysEdition sysEdition){
		
		sysEdition.setOrderBy(" create_time desc");
		sysEdition = sysEditionService.findOne(sysEdition);

		return new ObjectDataResponse<SysEdition>(sysEdition);
	}
	
	
	
	
    @IgnoreAuth
    @ApiOperation(value = "      用户注册", notes = "用户注册")
	@RequestMapping(value = "register", method = RequestMethod.POST)
	@ResponseBody
	public ApiRegisterResponse register(@RequestBody ApiRegisterRequest request) throws WriterException, IOException  {
     	ApiRegisterResponse response=new ApiRegisterResponse();
     	User user = null;
     	Map<String, Object> params = null;
     	
     	// 判断手机号码是否已注册
     	params = new HashMap<String, Object>();
 		params.put("phone", request.getParams().getPhone());
 		user = userService.findOne(params);
 		if(user != null) {
 			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
     		response.setResultMsg(ApiRestfulResponse.ERROR_PHONE_ALREADY_REGISTER);
     		return response;
 		}
     	
 		// 执行注册
 		user = this.register(request.getParams().getPhone(), 
 							 request.getParams().getPassword(),
 							 request.getParams().getNickname(),
 							 request.getParams().getSex(),
 							 request.getParams().getInviteCode(),
 							 request.getParams().getAvatar(),
 							 false,
 				             null		 
 				);
 		
 		if(user == null) {
 			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
     		response.setResultMsg(ApiRestfulResponse.ERROR_SYS_BUSY_MSG);
 			return response;
 		}
 		
 		//极光推送
 		User user2 = new User();
 		user2.setPhone(request.getParams().getPhone());
 		User user3 = userService.findOne(user2);
 		
 		if (user != null) {
			//生成消息
			Message message = new Message();
			message.setUserId(user3.getId());
			message.setType(1);
			message.setPushType(1);
			message.setContent("恭喜你加入！");
			message.setCreateTime(new Timestamp(new Date().getTime()));
			message.setTitle("注册成功");
			message.setRemark("注册成功");
			//推送消息
			messageService.insert(message);
			//极光推送
			try {
				MsgPushUtils.addJPush(message.getContent(), user3.getId().toString());
			} catch (Exception e) {
				logger.error("注册时发送几个推送消息失败 !"+user2.getPhone());
			}
		}
     	
		return response;
	}
	
    @IgnoreAuth
    @ApiOperation(value = "获取邀请有礼说明", notes = "获取邀请有礼说明")
	@RequestMapping(value = "getInviteConfig", method = RequestMethod.GET)
	@ResponseBody
	public String getInviteConfig(){
		
		InviteConfig inviteConfig = inviteConfigService.get(new Long(1));
		
		return inviteConfig.getInviteMsg();
	}

	@IgnoreAuth
    @ApiOperation(value = "H5用户注册", notes = "H5用户注册")
	@RequestMapping(value = "registerGMC", method = RequestMethod.GET)
	@ResponseBody
	public String registerGMC(String phone,String password,String qrCode,String userId) throws Exception{
     	User user = null;
     	Map<String, Object> params = null;
     	
     	// 判断手机号码是否已注册
     	params = new HashMap<String, Object>();
 		params.put("phone", phone);
 		user = userService.findOne(params);
 		if(user != null) {
 			
     		return ApiRestfulResponse.ERROR_PHONE_ALREADY_REGISTER;
 		}
 		
 		 //最新一条
 		User userEntity = userService.topUser(new User());
 		// 执行注册
 		user = this.register(phone, 
 				             password,
 				            String.valueOf(userEntity.getId()+1),
 							 "1",    //性别
 							 null, //邀请码
 							 null, //头像 
 							 false,
 							qrCode
 				); //是否传头像
 		//注册失败
 		if(user == null) {
 			return ApiRestfulResponse.ERROR_SYS_BUSY_MSG;
 		}
 		
        //插入邀请
 	    InviteHistory inviteHistory = new InviteHistory();
 	    inviteHistory.setUserId(Long.valueOf(userId));
 	    inviteHistory.setInviteUserId(user.getId());
 	    Timestamp time = new Timestamp(System.currentTimeMillis()); 
 	    inviteHistory.setInviteTime(time);
 	    inviteHistory.setIsLogin(0);
 		inviteHistoryService.insert(inviteHistory);
     	
		return "2";
		
	}
    
	/**
	 * 刷新用户Token
	 */
	@ResponseBody
	@ApiOperation(value = "刷新用户Token",notes = "刷新用户Token")
	@RequestMapping(value = "referToken", method = RequestMethod.POST)
	public ApiLoginResponse  referToken(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId)  {
		User user = userService.get(userId);
		if (user == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION,"用户不存在");
		}
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put(MagicConstants.SESSION_USER_ID,user.getId());
		Token token =null;
		try {
			token = TokenGenerator.create(claims);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JWTCreationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		ApiLoginResponse response=new ApiLoginResponse();
		ApiLoginResponseModel body = new ApiLoginResponseModel();
		
		body.setUserid(String.valueOf(user.getId()));
		body.setUserType(String.valueOf(user.getType()));
		body.setToken(token.getToken());
		
		response.setBody(body);
		
	    return response;
	}
    
    
    @IgnoreAuth
    @ApiOperation(value = "      用户登录", notes = "用户登录")
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public ApiLoginResponse login(HttpServletRequest request1,HttpServletResponse response1,@CurrentUserId Long userId,@RequestBody ApiLoginRequest request)  {
    		ApiLoginResponse response=new ApiLoginResponse();
    		ApiLoginResponseModel body = new ApiLoginResponseModel();
    		User user = null;
    		Map<String, Object> params = null;
    		UserLoginHistory userLoginHistory = null;
    		Timestamp currentDateTime = new Timestamp((new java.util.Date()).getTime());
    		
    		params = new HashMap<String, Object>();
    		params.put("phone", request.getParams().getPhone());
    		user = userService.findOne(params);
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
     		response.setResultMsg("你输入的手机号错误");
     		return response;
    		}
    		
    		if(!EncodeUtil.encodeMD5(request.getParams().getPassword()).equals(user.getPassword())) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
         	response.setResultMsg("你输入的密码错误");
         	return response;
    		}
    		
    		// 清除之前的登录历史
    		params = new HashMap<String, Object>();
    		params.put("userId", user.getId());
    		params.put("status", UserLoginHistory.LOGIN_STATUS_NO_LOGOUT);
    		List<UserLoginHistory> userLoginHistorys = userLoginHistoryService.find(params);
    		if(userLoginHistorys != null) {
    			for(int i = 0 ; i < userLoginHistorys.size(); i++) {
    				userLoginHistory = userLoginHistorys.get(i);
    				userLoginHistory.setStatus(UserLoginHistory.LOGIN_STATUS_LOGOUT);
    				userLoginHistory.setLogoutTime(currentDateTime);
    				userLoginHistoryService.update(userLoginHistory);
    			}
    		}
    		
    		// 添加登录历史
    		userLoginHistory = new UserLoginHistory();
    		userLoginHistory.setUserId(user.getId());
    		userLoginHistory.setType(UserLoginHistory.ACCOUNT_TYPE_PHONE);
    		userLoginHistory.setStatus(UserLoginHistory.LOGIN_STATUS_NO_LOGOUT);
    		userLoginHistory.setLoginTime(currentDateTime);
    		userLoginHistoryService.insert(userLoginHistory);
    		
    		body.setUserid(String.valueOf(user.getId()));
    		body.setUserType(String.valueOf(user.getType()));

    		//判断当前登录用户
    		distributionMsgService.handleLoginGetCredits(String.valueOf(user.getId()));
    		
    		Map<String, Object> claims = new HashMap<String, Object>();
    		claims.put(MagicConstants.SESSION_USER_ID, user.getId());
    		Token token=null;
			try {
				token = TokenGenerator.create(claims);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JWTCreationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		//留做测试使用
    		new CookieManager(request1, response1).setCookie(MagicConstants.USER_TOKEN,token.getToken(), 7*24*60*60*100);
    		body.setToken(token.getToken());
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      第三方用户登录", notes = "第三方用户登录")
	@RequestMapping(value = "thirdLogin", method = RequestMethod.POST)
	@ResponseBody
	public ApiThirdPartyLoginResponse thirdLogin(HttpServletRequest request1,HttpServletResponse response1,@RequestBody ApiThirdPartyLoginRequest request)  {
    		ApiThirdPartyLoginResponse response=new ApiThirdPartyLoginResponse();
    		ApiThirdPartyLoginResponseModel body = new ApiThirdPartyLoginResponseModel();
    		User user = null;
    		Map<String, Object> params = null;
    		UserLoginHistory userLoginHistory = null;
    		Timestamp currentDateTime = new Timestamp((new java.util.Date()).getTime());
        int thirdPartyType = 0;
        
        // 未进行有效性判断
    		
    		// 查询是否已绑定帐号
    		params = new HashMap<String, Object>();
    		switch(Integer.parseInt(request.getParams().getType())) {
    		case User.THIRD_PARTY_USER_QQ :
    			params.put("qqAccount", request.getParams().getOpenid());
    			thirdPartyType = UserLoginHistory.ACCOUNT_TYPE_QQ;
    			break;
    		case User.THIRD_PARTY_USER_WEIXIN :
    			params.put("weixinAccount", request.getParams().getOpenid());
    			thirdPartyType = UserLoginHistory.ACCOUNT_TYPE_WEIXIN;
    			break;
    		case User.THIRD_PARTY_USER_WEIBO :
    			params.put("weiboAccount", request.getParams().getOpenid());
    			thirdPartyType = UserLoginHistory.ACCOUNT_TYPE_WEIBO;
    			break;
    		default :
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
            response.setResultMsg(ApiRestfulResponse.ERROR_THIRD_PARTY_TYPE);
            return response;
    		}
    		user = userService.findOne(params);
    		
    		if(user != null) { 			// 如果绑定了直接登录
    			body.setIsUser("1");
        		body.setUserid(String.valueOf(user.getId()));
        		body.setUserType(String.valueOf(user.getType()));
    			
        		// 清除之前的登录历史
        		params = new HashMap<String, Object>();
        		params.put("userId", user.getId());
        		params.put("status", UserLoginHistory.LOGIN_STATUS_NO_LOGOUT);
        		List<UserLoginHistory> userLoginHistorys = userLoginHistoryService.find(params);
        		if(userLoginHistorys != null) {
        			for(int i = 0 ; i < userLoginHistorys.size(); i++) {
        				userLoginHistory = userLoginHistorys.get(i);
        				userLoginHistory.setStatus(UserLoginHistory.LOGIN_STATUS_LOGOUT);
        				userLoginHistory.setLogoutTime(currentDateTime);
        				userLoginHistoryService.update(userLoginHistory);
        			}
        		}
        		
        		// 添加登录历史
        		userLoginHistory = new UserLoginHistory();
        		userLoginHistory.setUserId(user.getId());
        		userLoginHistory.setType(thirdPartyType);
        		userLoginHistory.setStatus(UserLoginHistory.LOGIN_STATUS_NO_LOGOUT);
        		userLoginHistory.setLoginTime(currentDateTime);
        		userLoginHistoryService.insert(userLoginHistory);
        		
        		Map<String, Object> claims = new HashMap<String, Object>();
        		claims.put(MagicConstants.SESSION_USER_ID, user.getId());
        		Token token=null;
    			try {
    				token = TokenGenerator.create(claims);
    			} catch (IllegalArgumentException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (JWTCreationException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (UnsupportedEncodingException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
        		//留做测试使用
        		new CookieManager(request1, response1).setCookie(MagicConstants.USER_TOKEN,token.getToken(), 7*24*60*60*100);
        		body.setToken(token.getToken());
        		response.setBody(body);
    		} else {
    			body.setIsUser("0");
        		body.setUserid("0");
        		body.setUserType("0");
    		}
    		
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      第三方帐号绑定手机", notes = "第三方帐号绑定手机")
	@RequestMapping(value = "bindPhone", method = RequestMethod.POST)
	@ResponseBody
	public ApiBindPhoneResponse bindPhone(HttpServletRequest request1,HttpServletResponse response1,@RequestBody ApiBindPhoneRequest request) throws WriterException, IOException  {
    		ApiBindPhoneResponse response=new ApiBindPhoneResponse();
    		ApiBindPhoneResponseModel body = new ApiBindPhoneResponseModel();
    		User user = null;
     	Map<String, Object> params = null;
     	Timestamp currentDateTime = new Timestamp((new java.util.Date()).getTime());
     	UserLoginHistory userLoginHistory = null;
     	int thirdPartyType = 0;
     	
    		// 未进行有效性判断
    		// 未进行验证码验证
    		
     	params = new HashMap<String, Object>();
		params.put("phone", request.getParams().getPhone());
		user = userService.findOne(params);
		if(user == null) {			// 如果手机号未注册，先进行注册
			user = this.register(request.getParams().getPhone(), 
					 request.getParams().getPassword(),
					 request.getParams().getNickname(),
					 request.getParams().getSex(),
					 request.getParams().getInviteCode(),
					 request.getParams().getAvatar(),
					 true,
					 null);
			if(user == null) {
				response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
	     		response.setResultMsg(ApiRestfulResponse.ERROR_SYS_BUSY_MSG);
	 			return response;
			}
		} else {
			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
     		response.setResultMsg(ApiRestfulResponse.ERROR_PHONE_BINDED);
 			return response;
		}
		
		// 执行绑定
		switch(Integer.parseInt(request.getParams().getType())) {
		case User.THIRD_PARTY_USER_QQ :
			user.setQqAccount(request.getParams().getOpenid());
			thirdPartyType = UserLoginHistory.ACCOUNT_TYPE_QQ;
			break;
		case User.THIRD_PARTY_USER_WEIXIN :
			user.setWeixinAccount(request.getParams().getOpenid());
			thirdPartyType = UserLoginHistory.ACCOUNT_TYPE_WEIXIN;
			break;
		case User.THIRD_PARTY_USER_WEIBO :
			user.setWeiboAccount(request.getParams().getOpenid());
			thirdPartyType = UserLoginHistory.ACCOUNT_TYPE_WEIBO;
			break;
		default :
			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
			response.setResultMsg(ApiRestfulResponse.ERROR_THIRD_PARTY_TYPE);
			return response;
		}
		userService.update(user);
		
		// 清除之前的登录历史
		params = new HashMap<String, Object>();
		params.put("userId", user.getId());
		params.put("status", UserLoginHistory.LOGIN_STATUS_NO_LOGOUT);
		List<UserLoginHistory> userLoginHistorys = userLoginHistoryService.find(params);
		if(userLoginHistorys != null) {
			for(int i = 0 ; i < userLoginHistorys.size(); i++) {
				userLoginHistory = userLoginHistorys.get(i);
				userLoginHistory.setStatus(UserLoginHistory.LOGIN_STATUS_LOGOUT);
				userLoginHistory.setLogoutTime(currentDateTime);
				userLoginHistoryService.update(userLoginHistory);
			}
		}
		
		// 添加登录历史
		userLoginHistory = new UserLoginHistory();
		userLoginHistory.setUserId(user.getId());
		userLoginHistory.setType(thirdPartyType);
		userLoginHistory.setStatus(UserLoginHistory.LOGIN_STATUS_NO_LOGOUT);
		userLoginHistory.setLoginTime(currentDateTime);
		userLoginHistoryService.insert(userLoginHistory);
		
    	body.setUserid(String.valueOf(user.getId()));
    	body.setUserType(String.valueOf(user.getType()));
    	response.setBody(body);
    	
    	Map<String, Object> claims = new HashMap<String, Object>();
		claims.put(MagicConstants.SESSION_USER_ID, user.getId());
		Token token=null;
		try {
			token = TokenGenerator.create(claims);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JWTCreationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//留做测试使用
		new CookieManager(request1, response1).setCookie(MagicConstants.USER_TOKEN,token.getToken(), 7*24*60*60*100);
		body.setToken(token.getToken());
		response.setBody(body);
    	
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      忘记密码", notes = "忘记密码")
	@RequestMapping(value = "forgetPwd", method = RequestMethod.POST)
	@ResponseBody
	public ApiForgetPwdResponse forgetPwd(@RequestBody ApiForgetPwdRequest request)  {
    		ApiForgetPwdResponse response=new ApiForgetPwdResponse();
    		Map<String, Object> params = null;
    		User user = null;
    		
    		// 未进行有效性判断
    		// 未进行验证码验证
    		
    		// 判断手机号码是否已注册
    		params = new HashMap<String, Object>();
    		params.put("phone", request.getParams().getPhone());
    		user = userService.findOne(params);
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_PHONE_NOT_REGISTER);
    			return response;
    		}
    		
    		user.setPassword(EncodeUtil.encodeMD5(request.getParams().getPassword()));
    		userService.update(user);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      修改密码", notes = "忘记密码")
	@RequestMapping(value = "changePwd", method = RequestMethod.POST)
	@ResponseBody
	public ApiChangePwdResponse changePwd(@RequestBody ApiChangePwdRequest request)  {
    		ApiChangePwdResponse response=new ApiChangePwdResponse();
    		ApiChangePwdResponseModel body = new ApiChangePwdResponseModel();
    		User user = null;
    		
    		// 未进行有效性判断
    		
    		user = isLogin(Long.parseLong(request.getParams().getUserid()));
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		if(!EncodeUtil.encodeMD5(request.getParams().getOldPassword()).equals(user.getPassword())) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_OLD_PASSWORD);
    			return response;
    		}
    		
    		user.setPassword(EncodeUtil.encodeMD5(request.getParams().getNewPassword()));
    		userService.update(user);
    		
    		body.setCode("1234");
    		response.setBody(body);
		return response;
	}
    

    
    
    @IgnoreAuth
    @ApiOperation(value = "H5获取验证码" , notes="H5获取验证码")
	@RequestMapping(value = "getGMC", method = RequestMethod.GET)
	@ResponseBody
	public int getGMC(String phone) throws Exception{
    	Code code = null;
    	
    	//在1000-10000之间随机获取一个数值 作为你的 手机验证码
		CONTENT_CODE = (int)((Math.random()*9+1)*100000);
		String sendedCode = String.valueOf(CONTENT_CODE);
		String CONTENT ="您的验证码是："+CONTENT_CODE+"。请不要把验证码泄露给其他人。";
    	
        Map<String, Object> params = null;
     	
     	// 判断手机号码是否已注册
     	params = new HashMap<String, Object>();
 		params.put("phone", phone);
 		User user = userService.findOne(params);
 		if(user != null) {
     		return 1; //此手机号已注册！
 		}
		
		
		//短信注入
		HttpClientUtil  httpClientUtil = new HttpClientUtil(); 
		Map<String,String> createMap = new HashMap<String,String>();  
        createMap.put("account",MESSAGE_APIID);  //APIID
        createMap.put("password",MESSAGE_PASSWORD);  
        createMap.put("mobile",phone); 
        createMap.put("content",CONTENT);  
        long epoch = System.currentTimeMillis()/1000;
        createMap.put("time",String.valueOf(epoch));  
        createMap.put("format","xml");//设置返回值类型  
        
        String result = httpClientUtil.doPost(MESSAGE_URL, createMap, "utf-8");
        
        
        SysConfig sysConfig = getSysConfig(SysConfig.CONFIG_SMS_CODE_EXPIRE_TIME);
   		Timestamp currentDateTime = new Timestamp((new java.util.Date()).getTime());
   		int expiredTime = (sysConfig != null) ? Integer.parseInt(sysConfig.getValue()) : 120;
       Timestamp expiredDateTime = new Timestamp((new java.util.Date()).getTime() + expiredTime);
       String tokenStr = String.format("%04d%02d%02d%02d%02d%02d%04d", 
       		                            currentDateTime.getYear(),
       		                            currentDateTime.getMonth(),
       		                            currentDateTime.getDay(),
       		                            currentDateTime.getHours(),
       		                            currentDateTime.getMinutes(),
       		                            currentDateTime.getSeconds(),
       		                            currentDateTime.getNanos());

        code = new Code();
		code.setType(1);
		code.setCode(sendedCode);
		code.setPhone(phone);
		code.setCreateTime(currentDateTime);
		
		code.setExpireTime(expiredDateTime);
		code.setToken(UserTokenGenerator.encode(tokenStr));
		code.setStatus(Code.STATUS_NOT_USE);
		codeService.insert(code);

        return CONTENT_CODE;
		

	}
    
    @IgnoreAuth
    @ApiOperation(value = "获取验证码（新）" , notes="获取验证码（新）")
	@RequestMapping(value = "getNewCode", method =  {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public int getNewCode(String phone) throws UnsupportedEncodingException{
 
    	Map<String, Object> params = new HashMap<String, Object>();
		params.put("phone", phone);
		User user = userService.findOne(params);
		//该用户已经存在不能发送验证码注册
		if(user!=null){
			return 1;
		}

		//在1000-10000之间随机获取一个数值 作为你的 手机验证码
		CONTENT_CODE = (int)((Math.random()*9+1)*100000);
		//String CONTENT = "您的验证码:"+CONTENT_CODE+"，1分钟内有效。";
		String CONTENT ="您的验证码是："+CONTENT_CODE+"。请不要把验证码泄露给其他人。";
				
		HttpClientUtil  httpClientUtil = new HttpClientUtil();  
       Map<String,String> createMap = new HashMap<String,String>();  
       createMap.put("account",MESSAGE_APIID);  //APIID
       createMap.put("password",MESSAGE_PASSWORD);  
       createMap.put("mobile",phone); 
       createMap.put("content",CONTENT);  
       long epoch = System.currentTimeMillis()/1000;
       createMap.put("time",String.valueOf(epoch));  
       createMap.put("format","xml");//设置返回值类型  
       
        String result = httpClientUtil.doPost(MESSAGE_URL, createMap, "utf-8");
		System.out.println("------------------>>>>>>>>>" + result);
		int len1 = result.indexOf("</code>");
		int len2 = result.indexOf("<code>");
		String resultCode = result.substring((len2+6), len1);//返回值
		
	    //获取返回信息
		int len3 = result.indexOf("</msg>");
		int len4 = result.indexOf("<msg>");
		String msg = result.substring((len4 + 5), len3);
		
		if (!(resultCode != null && !resultCode.equals("") && resultCode.trim().equals("2"))) {//不成功
			return 0;
		}
		
        return CONTENT_CODE;

	}

    @SuppressWarnings("deprecation")
	@IgnoreAuth
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
	@RequestMapping(value = "getCode", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetCodeResponse getCode(@RequestBody ApiGetCodeRequest request) throws UnsupportedEncodingException  {
    	
//    	ApiGetCodeResponse response=new ApiGetCodeResponse();
//   		ApiGetCodeResponseModel body = new ApiGetCodeResponseModel();
//   		Code code = null;
//   		User user = null;
//   		Map<String, Object> params = null;
//   		
//   		
//   		//1:注册，2：绑定手机，3：找回密码，4：修改密码
//   		params = new HashMap<String, Object>();
//   		params.put("phone", request.getParams().getPhone());
//   		user = userService.findOne(params);
//   		if(Integer.parseInt(request.getParams().getType()) == Code.TYPE_REGISTER && user != null) {//注册
//   			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
//   			response.setResultMsg(ApiRestfulResponse.ERROR_PHONE_ALREADY_REGISTER);
//   			return response;
//   		}
//   		if((Integer.parseInt(request.getParams().getType()) == Code.TYPE_RETRIEVE_PASSWORD ||
//   			Integer.parseInt(request.getParams().getType()) == Code.TYPE_CHANGE_PASSWORD) && user == null) {//找回密码 或者 修改密码
//   			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
//   			response.setResultMsg(ApiRestfulResponse.ERROR_PHONE_NOT_REGISTER);
//   			return response;
//   		}
//   		if(Integer.parseInt(request.getParams().getType()) == Code.TYPE_BIND_PHONE && user != null) {//绑定手机
//   			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
//   			response.setResultMsg(ApiRestfulResponse.ERROR_PHONE_BINDED);
//   			return response;
//   		}
//   		
//   		
//   		
//   	//在1000-10000之间随机获取一个数值 作为你的 手机验证码
//		CONTENT_CODE = (int)((Math.random()*9+1)*100000);
//		String sendedCode = String.valueOf(CONTENT_CODE); 
//		
// 		String accesskey = "PUP8rOfAzxCHlCAX"; //用户开发key
//        String accessSecret = "Ylj3lvk20lUrFrVnzCvu5vW0HUqIajiu"; //用户开发秘钥
//
//		//短信注入
//		HttpClientUtil  httpClientUtil = new HttpClientUtil(); 
//		Map<String,String> createMap = new HashMap<String,String>();  
//        createMap.put("accesskey",accesskey);  
//        createMap.put("secret",accessSecret);  
//        createMap.put("sign","2006"); //签名
//        createMap.put("templateId","3492");  //模板
//        createMap.put("mobile",request.getParams().getPhone());  
//        createMap.put("content",URLEncoder.encode(sendedCode, "utf-8"));//（示例模板：{1}您好，您的订单于{2}已通过{3}发货，运单号{4}）
//        
//        String result = httpClientUtil.doPost("http://api.1cloudsp.com/api/v2/send", createMap, "utf-8");
//   		
//   		
//   		
////   		System.out.println("------------------>>>>>>>>>" + result);
////   		int len1 = result.indexOf("</code>");
////   		int len2 = result.indexOf("<code>");
////   		String resultCode = result.substring((len2+6), len1);//返回值
////   		
////   	    //获取返回信息
////   		int len3 = result.indexOf("</msg>");
////   		int len4 = result.indexOf("<msg>");
////   		String msg = result.substring((len4 + 5), len3);
////   		if (!(resultCode != null && !resultCode.equals("") && resultCode.trim().equals("2"))) {//不成功
////   			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
////   			response.setResultMsg(msg);
////   			return response;
////			}
//   		
//   		SysConfig sysConfig = getSysConfig(SysConfig.CONFIG_SMS_CODE_EXPIRE_TIME);
//   		Timestamp currentDateTime = new Timestamp((new java.util.Date()).getTime());
//   		int expiredTime = (sysConfig != null) ? Integer.parseInt(sysConfig.getValue()) : 120;
//       Timestamp expiredDateTime = new Timestamp((new java.util.Date()).getTime() + expiredTime);
//       String tokenStr = String.format("%04d%02d%02d%02d%02d%02d%04d", 
//       		                            currentDateTime.getYear(),
//       		                            currentDateTime.getMonth(),
//       		                            currentDateTime.getDay(),
//       		                            currentDateTime.getHours(),
//       		                            currentDateTime.getMinutes(),
//       		                            currentDateTime.getSeconds(),
//       		                            currentDateTime.getNanos());
//       		
//       
//       try {
//	        	code = new Code();
//	    		code.setType(Integer.parseInt(request.getParams().getType()));
//	    		code.setCode(sendedCode);
//	    		code.setPhone(request.getParams().getPhone());
//	    		code.setCreateTime(currentDateTime);
//	    		
//	    		code.setExpireTime(expiredDateTime);
//	    		code.setToken(UserTokenGenerator.encode(tokenStr));
//	    		code.setStatus(Code.STATUS_NOT_USE);
//	    		codeService.insert(code);
//		} catch (Exception e) {
//			e.printStackTrace();
//			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
//			response.setResultMsg(ApiRestfulResponse.ERROR_SYS_BUSY_MSG);
//			return response;
//		}
//   		
//   		body.setCode(sendedCode);
//   		response.setBody(body);
//		return response;
    	
    	
    		ApiGetCodeResponse response=new ApiGetCodeResponse();
    		ApiGetCodeResponseModel body = new ApiGetCodeResponseModel();
    		Code code = null;
    		User user = null;
    		Map<String, Object> params = null;

    		//1:注册，2：绑定手机，3：找回密码，4：修改密码
    		params = new HashMap<String, Object>();
    		params.put("phone", request.getParams().getPhone());
    		user = userService.findOne(params);
    		if(Integer.parseInt(request.getParams().getType()) == Code.TYPE_REGISTER && user != null) {//注册
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_PHONE_ALREADY_REGISTER);
    			return response;
    		}
    		if((Integer.parseInt(request.getParams().getType()) == Code.TYPE_RETRIEVE_PASSWORD ||
    			Integer.parseInt(request.getParams().getType()) == Code.TYPE_CHANGE_PASSWORD) && user == null) {//找回密码 或者 修改密码
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_PHONE_NOT_REGISTER);
    			return response;
    		}
    		if(Integer.parseInt(request.getParams().getType()) == Code.TYPE_BIND_PHONE && user != null) {//绑定手机
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_PHONE_BINDED);
    			return response;
    		}
    		
    		
    		 //在1000-10000之间随机获取一个数值 作为你的 手机验证码
    		CONTENT_CODE = (int)((Math.random()*9+1)*100000);
    		String sendedCode = String.valueOf(CONTENT_CODE);
    		//String CONTENT = "您的验证码:"+CONTENT_CODE+"，1分钟内有效。";
    		String CONTENT ="您的验证码是："+CONTENT_CODE+"。请不要把验证码泄露给其他人。";
    				
			HttpClientUtil  httpClientUtil = new HttpClientUtil();  
	        Map<String,String> createMap = new HashMap<String,String>();  
	        createMap.put("account",MESSAGE_APIID);  //APIID
	        createMap.put("password",MESSAGE_PASSWORD);  
	        createMap.put("mobile",request.getParams().getPhone()); 
	        createMap.put("content",CONTENT);  
	        long epoch = System.currentTimeMillis()/1000;
	        createMap.put("time",String.valueOf(epoch));  
	        createMap.put("format","xml");//设置返回值类型  
	        
	        String result = httpClientUtil.doPost(MESSAGE_URL, createMap, "utf-8");
    		System.out.println("------------------>>>>>>>>>" + result);
    		int len1 = result.indexOf("</code>");
    		int len2 = result.indexOf("<code>");
    		String resultCode = result.substring((len2+6), len1);//返回值
    		
    	    //获取返回信息
    		int len3 = result.indexOf("</msg>");
    		int len4 = result.indexOf("<msg>");
    		String msg = result.substring((len4 + 5), len3);
    		if (!(resultCode != null && !resultCode.equals("") && resultCode.trim().equals("2"))) {//不成功
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(msg);
    			return response;
			}
    		
    		SysConfig sysConfig = getSysConfig(SysConfig.CONFIG_SMS_CODE_EXPIRE_TIME);
    		Timestamp currentDateTime = new Timestamp((new java.util.Date()).getTime());
    		int expiredTime = (sysConfig != null) ? Integer.parseInt(sysConfig.getValue()) : 120;
        Timestamp expiredDateTime = new Timestamp((new java.util.Date()).getTime() + expiredTime);
        String tokenStr = String.format("%04d%02d%02d%02d%02d%02d%04d", 
        		                            currentDateTime.getYear(),
        		                            currentDateTime.getMonth(),
        		                            currentDateTime.getDay(),
        		                            currentDateTime.getHours(),
        		                            currentDateTime.getMinutes(),
        		                            currentDateTime.getSeconds(),
        		                            currentDateTime.getNanos());
        		
        
        try {
	        	code = new Code();
	    		code.setType(Integer.parseInt(request.getParams().getType()));
	    		code.setCode(sendedCode);
	    		code.setPhone(request.getParams().getPhone());
	    		code.setCreateTime(currentDateTime);
	    		
	    		code.setExpireTime(expiredDateTime);
	    		code.setToken(UserTokenGenerator.encode(tokenStr));
	    		code.setStatus(Code.STATUS_NOT_USE);
	    		codeService.insert(code);
		} catch (Exception e) {
			e.printStackTrace();
			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
			response.setResultMsg(ApiRestfulResponse.ERROR_SYS_BUSY_MSG);
			return response;
		}
    		
    		body.setCode(sendedCode);
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取用户信息", notes = "获取用户信息")
	@RequestMapping(value = "getUserInfo", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetUserInfoResponse getUserInfo(@RequestBody ApiGetUserInfoRequest request)  {
    		ApiGetUserInfoResponse response=new ApiGetUserInfoResponse();
    		ApiGetUserInfoResponseModel body = new ApiGetUserInfoResponseModel();
    		User user = null;
    		Map<String, Object> params = null;
    		Shop shop = null;
    		
    		// 未进行有效性判断
    		
    		user = getUser(Long.parseLong(request.getParams().getUserid()));
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_USER_NOT_EXIST);
    			return response;
    		}
    		
    		body.setAvatar(getAbsoulteImageUrl(user.getPortrait()));
    		body.setNickname(getNickName(user));
    		body.setPhone(user.getPhone());
    		body.setSex(user.getSex() == User.SEX_MALE ? "0" : "1");
    		body.setBirtyday(getStringDate(user.getBirthday()));
    		//等级
    		body.setLevel(user.getType());
    		
    		Area area = getPrevAddress(user.getRegionId());
    		if(area != null) {
	    		body.setRegionId(String.valueOf(area.getRegionId()));
	    		body.setCityId(String.valueOf(area.getCityId()));
	    		body.setProvinceId(String.valueOf(area.getProvinceId()));
	    		body.setAddress(area.getAddress());
    		} else {
    			body.setProvinceId("0");
    			body.setCityId("0");
    			body.setRegionId("0");
    			body.setAddress("");
    		}
    		body.setIsVip(user.getLevel() == 0 ? "0" : "1");
    		body.setVipNum(user.getMemberCard());
    		body.setBalance(String.valueOf(user.getBalance()));
    		body.setIntegral(String.valueOf(user.getPoints()));
    		body.setRebate(String.valueOf(user.getCanRebateBalance()));
    		body.setWithdraw(String.valueOf(user.getCanWithdrawBalance()));
    		body.setUserLevel(user.getUserLevel());
    		User user2 = userDao.getGoodRebate(user);
    		if(user2!=null){
    			body.setGoodRebate(user2.getGoodRebate());
    		}else{
    			body.setGoodRebate(0.0f);
    		}
    		
    		body.setVipRebate(user.getVipRebate());
    		body.setVipBalance(user.getVipBalance());
    		body.setVipBalanceSum(user.getVipBalanceSum());
    		
    		//是否绑定银行卡
    		if (user.getIsBank() == null) {
    			body.setIsBank(1);
			}else {
				body.setIsBank(user.getIsBank());
			}
    		
    		params = new HashMap<String, Object>();
    		params.put("userId", user.getId());
    		params.put("status", Shop.STATUS_OK);
    		shop = shopService.findOne(params);
    		body.setIsJoin(shop == null ? "0" : "1");
    		response.setBody(body);
		return response;
	}
    
    @SuppressWarnings("deprecation")
	@IgnoreAuth
    @ApiOperation(value = "      更新用户信息", notes = "更新用户信息")
	@RequestMapping(value = "updateUserInfo", method = RequestMethod.POST)
	@ResponseBody
	public ApiUpdateUserInfoResponse updateUserInfo(@RequestBody ApiUpdateUserInfoRequest request)  {
    		ApiUpdateUserInfoResponse response=new ApiUpdateUserInfoResponse();
    		User user = isLogin(Long.parseLong(request.getParams().getUserid()));
    		
    		// 未进行有效性判断
    		
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		switch(Integer.parseInt(request.getParams().getType())) {
    		case ApiUpdateUserInfoRequest.TYPE_AVATAR :
    			user.setPortrait(request.getParams().getNewValue());
    			break;
    		case ApiUpdateUserInfoRequest.TYPE_NICKNAME :
    			user.setNickname(request.getParams().getNewValue());
    			break;
    		case ApiUpdateUserInfoRequest.TYPE_PHONE :
    			user.setPhone(request.getParams().getNewValue());
    			break;
    		case ApiUpdateUserInfoRequest.TYPE_SEX :
    			break;
    		case ApiUpdateUserInfoRequest.TYPE_MEMBERCARD :
    			user.setMemberCard(request.getParams().getNewValue());
    			break;
    		case ApiUpdateUserInfoRequest.TYPE_BIRTHDAY :
    			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    			java.util.Date date = null;
    			try {
    			    date = sdf.parse(request.getParams().getNewValue());
    			} catch (ParseException e) {
    			    e.printStackTrace();
    			    response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
        			response.setResultMsg(ApiRestfulResponse.ERROR_SYS_BUSY_MSG);
        			return response;
    			}
    			user.setBirthday(new Timestamp((new Date(date.getYear(),date.getMonth(),date.getDate())).getTime()));
    			break;
    		case ApiUpdateUserInfoRequest.TYPE_AREA :
    			user.setRegionId(Long.parseLong(request.getParams().getNewValue()));
    			break;
    		default :
    			break;
    		}
    		
    		userService.update(user);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取首页信息", notes = "获取首页信息")
	@RequestMapping(value = "getHomeInfo", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetHomeInfoResponse getHomeInfo(@RequestBody ApiGetHomeInfoRequest request)  {
    		ApiGetHomeInfoResponse response=new ApiGetHomeInfoResponse();
    		ApiGetHomeInfoResponseModel body = new ApiGetHomeInfoResponseModel();
    		List<ApiGetHomeInfoResponseModelBannerList> bannerList = new ArrayList<ApiGetHomeInfoResponseModelBannerList>();
    	    List<ApiGetHomeInfoResponseModelNoticeList> noticeList = new ArrayList<ApiGetHomeInfoResponseModelNoticeList>();
    	    ApiGetHomeInfoResponseModelNewsInfo newsInfo = new ApiGetHomeInfoResponseModelNewsInfo();
    	    List<ApiGetHomeInfoResponseModelSaleList> saleList = new ArrayList<ApiGetHomeInfoResponseModelSaleList>();
    	    List<ApiGetHomeInfoResponseModelActivityList> activityList = new ArrayList<ApiGetHomeInfoResponseModelActivityList>();
    	    List<ApiGetHomeInfoResponseModelHotList> hotList = new ArrayList<ApiGetHomeInfoResponseModelHotList>();
    		List<Banner> banners = null;
    		List<Notice> notices = null;
    		Notice ntc = null;
    		News news = null;
    		List<Goods> goodss = null;
    		Goods goods = null;
    		GoodsImage goodsImage = null;
    		List<Activity> activitys = null;
    		Activity act = null;
    		Map<String, Object> params = null;
    		ApiGetHomeInfoResponseModelBannerList banner = null;
    		ApiGetHomeInfoResponseModelNoticeList notice = null;
    		ApiGetHomeInfoResponseModelSaleList sale = null;
    	    ApiGetHomeInfoResponseModelActivityList activity = null;
    	    ApiGetHomeInfoResponseModelHotList hot = null;
    		int i = 0;
    	    
    	    // banner list, 
    		params = new HashMap<String, Object>();
    		params.put("status", Banner.STATUS_VALID);
    		params.put("isDisplay", 0);
    		params.put("isOpen", 0);
    	    banners = bannerService.find(params);
    	    for(Banner b : banners)  {
    	    		banner = new ApiGetHomeInfoResponseModelBannerList();
    	    		switch(b.getSkipType()) {
    	    		case Banner.SKIP_TYPE_NONE :
    	    			banner.setType(String.valueOf(ApiGetHomeInfoResponseModelBannerList.TYPE_NONE));
    	    			break;
    	    		case Banner.SKIP_TYPE_WEB :
    	    			banner.setType(String.valueOf(ApiGetHomeInfoResponseModelBannerList.TYPE_URL));
    	    			break;
    	    		case Banner.SKIP_TYPE_GOODS :
    	    			banner.setType(String.valueOf(ApiGetHomeInfoResponseModelBannerList.TYPE_GOODS));
    	    			break;
    	    		case Banner.SKIP_TYPE_ACTIVITY :
    	    			banner.setType(String.valueOf(ApiGetHomeInfoResponseModelBannerList.TYPE_ACTIVITY));
    	    			break;
    	    		default :
    	    			break;
    	    		}
    	    		banner.setLink(b.getSkipMsg());
        	    banner.setTitle(b.getRemark());
        	    banner.setIcon(getAbsoulteImageUrl(b.getImage()));
        	    bannerList.add(banner);
    	    }
    	    
    	    // notice list
    		params = new HashMap<String, Object>();
    	    notices = noticeService.find(params);
    	    for(i = 0 ; i < notices.size(); i++) {
    	    		ntc = notices.get(i);
    	    		notice = new ApiGetHomeInfoResponseModelNoticeList();
    	    		notice.setType(String.valueOf(ntc.getType()));
    	    	    notice.setTitle(ntc.getTitle());
    	    	    notice.setLink(ntc.getContent());
    	    	    noticeList.add(notice);
    	    }
    	    
    	    // news info
    	    params = new HashMap<String, Object>();
    	    params.put("status", News.STATUS_VALID);
    	    params.put("orderBy", "show_time desc");
    	    params.put("showTime", "1");
    	    news = newsService.findOne(params);
    	    if(news != null) {
    	    		newsInfo.setId(String.valueOf(news.getId()));
        	    newsInfo.setDetail(StringUtils.delHTMLTag(news.getContent()));
        	    newsInfo.setIcon(getAbsoulteImageUrl(news.getCover()));
        	    newsInfo.setTitle(news.getTitle());
    	    } else {
    	    		newsInfo.setId("0");
        	    newsInfo.setDetail("");
        	    newsInfo.setIcon("");
        	    newsInfo.setTitle("");
    	    }
    	    
    	    // goods info
    	   /* params = new HashMap<String, Object>();
    	    params.put("isSpecialPrice", 1);
    	    params.put("status", Goods.STATUS_SELLING);
    	    params.put("isTravelGoods", 0);
    	    params.put("isOpenSpecial", 1);
    	    params.put("orderBy", "create_time desc");*/
    	    
    	    Goods saGood=new Goods();
    	    saGood.setIsSpecialPrice(1);
    	    saGood.setIsTravelGoods(0);
    	    goodss=goodsdao.findAllGoods2(saGood);
    	    
    	    List<Goods> list2=new ArrayList<Goods>();	
    	    for (int j = 0; j < goodss.size(); j++) {
				Goods goods2=goodss.get(j);
				
	           if (goods2.getIsSpecialPrice()==1) {
			    	
			    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
					String date = df.format(new Date());
					Timestamp.valueOf(date);
					long now=new Date().getTime();
					if (now>goods2.getSpecialStartTime().getTime() && now<goods2.getSpecialEndTime().getTime() ) {
						 list2.add(goods2);
					}
				}
			}
    	    for(i = 0 ; i < list2.size(); i++) {
    	    		goods = list2.get(i);
    	    		sale = new ApiGetHomeInfoResponseModelSaleList();
    	    		sale.setId(String.valueOf(goods.getId()));
    	    	    sale.setPrice(String.valueOf(goods.getSpecialPrice()));
    	    	    sale.setTitle(goods.getName());
    	    	    sale.setCount(String.valueOf(goods.getInventory()));
    	    	    params = new HashMap<String, Object>();
    	    	    params.put("goodsId", goods.getId());
    	    	    goodsImage = goodsImageService.findOne(params);
    	    	    sale.setIcon(goodsImage != null ? getAbsoulteImageUrl(goodsImage.getImage()) : "");
    	    	    sale.setIsTravel(String.valueOf(goods.getIsTravelGoods()));
    	    	    sale.setType(String.valueOf(goods.getType()));
    	    	    saleList.add(sale);
    	    }
    	    
    	    // activity list
    	    updateActivityStatus();
    	    params = new HashMap<String, Object>();
    	    params.put("isRecommend", 1);
    	    params.put("existFlag", 0);
    	    //params.put("status", Activity.STATUS_BEING);
    	    params.put("orderBy", "create_time desc");
    	    activitys = activityService.find(params);
    	    for(i = 0 ; i < activitys.size(); i++) {
    	    		act = activitys.get(i);
    	    		activity = new ApiGetHomeInfoResponseModelActivityList();
    	    	    activity.setId(String.valueOf(act.getId()));
    	    	    Area area = getPrevAddress(act.getRegionId());
    	    		if(area != null) {
    	    			activity.setAddress(area.getAddress() + act.getAddrDetail());
    	    		} else {
    	    			activity.setAddress(act.getAddrDetail());
    	    		}
    	    	    activity.setIcon(act.getCoverImage() != null ? getAbsoulteImageUrl(act.getCoverImage()) : "");
    	    	    activity.setPrice(String.valueOf(act.getPrice()));
    	    	    activity.setTime(getStringDate(act.getCreateTime()));
    	    	    activity.setTitle(act.getTitle());
    	    	    activityList.add(activity);
    	    }
    	    
    	    // hot goods list
    	    params = new HashMap<String, Object>();
    	    params.put("isTravelGoods", 0);
    	    params.put("status", Goods.STATUS_SELLING);
    	    params.put("orderBy", "GOODS.sold_count  desc,GOODS.create_time desc");
    	    params.put("limitStart", 0);
    	    params.put("limitEnd", 5);
    	    goodss = goodsService.find(params);
    	    for(i = 0 ; i < goodss.size(); i++) {
	    		goods = goodss.get(i);
	    		hot = new ApiGetHomeInfoResponseModelHotList();
	    	    hot.setId(String.valueOf(goods.getId()));
	    	    hot.setCount(String.valueOf(goods.getSoldCount()));
	    	    hot.setPrice(String.valueOf(getGoodsPrice(goods)));
	    	    hot.setTitle(goods.getName());
	    	    hot.setUnit(goods.getSpec());
	    	    params = new HashMap<String, Object>();
	    	    params.put("goodsId", goods.getId());
	    	    goodsImage = goodsImageService.findOne(params);
	    	    hot.setIcon(goodsImage != null ? getAbsoulteImageUrl(goodsImage.getImage()) : "");
	    	    hot.setType(String.valueOf(goods.getType()));
	    	    hotList.add(hot);
	    }
    	    
    	    body.setBannerList(bannerList);
    	    body.setNoticeList(noticeList);
    	    body.setNewsInfo(newsInfo);
    	    body.setSaleList(saleList);
    	    body.setActivityList(activityList);
    	    body.setHotList(hotList);
    	    response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取天下行分类接口", notes = "获取天下行分类接口")
	@RequestMapping(value = "getTourType", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetTourTypeResponse getTourType(@RequestBody ApiGetTourTypeRequest request)  {
    		ApiGetTourTypeResponse response=new ApiGetTourTypeResponse();
    		ApiGetTourTypeResponseModel body = new ApiGetTourTypeResponseModel();
    		List<ApiGetTourTypeResponseModelList> list = new ArrayList<ApiGetTourTypeResponseModelList>();
    		ApiGetTourTypeResponseModelList data = null;
    		List<GoodsCategory> goodsCategorys = null;
    		GoodsCategory goodsCategory = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		
    		params = new HashMap<String, Object>();
    		params.put("type", GoodsCategory.TYPE_TRAVEL);
    		goodsCategorys = goodsCategoryService.find(params);
    		if(goodsCategorys != null) {
    			for(i = 0 ; i < goodsCategorys.size() ; i++) {
    				goodsCategory = goodsCategorys.get(i);
    				data = new ApiGetTourTypeResponseModelList();
	    	    		data.setId(String.valueOf(goodsCategory.getId()));
	    	    		data.setName(goodsCategory.getName());
	    	    		list.add(data);
    			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取天下行列表接口", notes = "获取天下行列表接口")
	@RequestMapping(value = "getTourList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetTourListResponse getTourList(@RequestBody ApiGetTourListRequest request)  {
    		ApiGetTourListResponse response=new ApiGetTourListResponse();
    		ApiGetTourListResponseModel body = new ApiGetTourListResponseModel();
    		List<ApiGetTourListResponseModelList> list = new ArrayList<ApiGetTourListResponseModelList>();
    		ApiGetTourListResponseModelList data = null;
    		List<Goods> goodss = null;
    		GoodsCategory goodsCategory = null;
    		Goods goods = null;
    		GoodsImage goodsImage = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		int page = (request.getParams().getPage() != null && !request.getParams().getPage().equals("")) ? 
  				   Integer.valueOf(request.getParams().getPage()) : 1;
  		int num 	=  (request.getParams().getNum() != null && !request.getParams().getNum().equals("")) ? 
 				   Integer.valueOf(request.getParams().getNum()) : 20;
    		
    		// 排序未做
    		
    		params = new HashMap<String, Object>();
    		if(request.getParams().getType() != null && Long.parseLong(request.getParams().getType()) > 0) {
    			params.put("categoryId", Long.parseLong(request.getParams().getType()));
    		}
    		params.put("type", Goods.TYPE_TRAVEL);
    		params.put("isTravelGoods", 1);
    		switch(Integer.parseInt(request.getParams().getSort())) {
    		case ApiGetTourListRequest.SORT_ALL :	// TODO
    			break;
    		case ApiGetTourListRequest.SORT_VIEW_COUNT :
    			params.put("orderBy", "GOODS.inventory - GOODS.remain_inventory desc");
    			break;
    		case ApiGetTourListRequest.SORT_PRICE :
    			params.put("orderBy", "price asc");
    			break;
    		case ApiGetTourListRequest.SORT_ELITE :	// TODO
    			break;
    		default :
    			break;
    		}
    		params.put("limitStart", getLimitStart(page,num));
    		params.put("limitEnd", getLimitEnd(page,num));
    		goodss = goodsService.find(params);
    		
    		if(goodss != null) {
    			for(i = 0 ; i < goodss.size(); i++) {
    				goods = goodss.get(i);
    				data = new ApiGetTourListResponseModelList();
	    	    		data.setCount(String.valueOf(getGoodsOrderCount(goods.getId())));
	    	    		data.setDetail(goods.getDetail());
	    	    		params = new HashMap<String, Object>();
	    	    	    params.put("goodsId", goods.getId());
	    	    	    goodsImage = goodsImageService.findOne(params);
	    	    		data.setIcon(goodsImage != null ? getAbsoulteImageUrl(goodsImage.getImage()) : "");
	    	    		data.setId(String.valueOf(goods.getId()));
	    	    		data.setPrice(String.valueOf(getGoodsPrice(goods)));
	    	    		data.setReview(String.valueOf(goods.getReview()));
	    	    		data.setSavePrice(String.valueOf(goods.getMarketPrice() - goods.getPrice()));
//	    	    		Area area = this.getPrevAddress(goods.getPlaceCityId());		// 需要改
//	    	    		if(area != null) {
//	    	    			data.setStarting(area.getAddress());
//	    	    		} else {
//	    	    			data.setStarting("");
//	    	    		}
	    	    		data.setStarting(goods.getPlaceCityId());
	    	    		data.setTitle(goods.getName());
	    	    		params = new HashMap<String, Object>();
	    	    		params.put("id", goods.getCategoryId());
	    	    		goodsCategory = goodsCategoryService.findOne(params);
	    	    		if(goodsCategory != null) {
	    	    			data.setTypeStr(goodsCategory.getName());
	    	    		} else {
	    	    			data.setTypeStr("");
	    	    		}
	    	    		
	    	    		list.add(data);
    			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取资讯列表接口", notes = "获取资讯列表接口")
	@RequestMapping(value = "getNewsList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetNewsListResponse getNewsList(@RequestBody ApiGetNewsListRequest request)  {
    		ApiGetNewsListResponse response=new ApiGetNewsListResponse();
    		ApiGetNewsListResponseModel body = new ApiGetNewsListResponseModel();
    		List<ApiGetNewsListResponseModelList> list = new ArrayList<ApiGetNewsListResponseModelList>();
    		ApiGetNewsListResponseModelList data = null;
    		List<News> newss = null;
    		News news = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		int page = (request.getParams().getPage() != null && !request.getParams().getPage().equals("")) ? 
 				   Integer.valueOf(request.getParams().getPage()) : 1;
 		    int num =  (request.getParams().getNum() != null && !request.getParams().getNum().equals("")) ? 
				   Integer.valueOf(request.getParams().getNum()) : 20;
			
    		params = new HashMap<String, Object>();
    		params.put("showTime", "1");
    		params.put("status", News.STATUS_VALID);
    	    params.put("orderBy", "show_time desc");
    		params.put("limitStart", getLimitStart(page,num));
    		params.put("limitEnd", getLimitEnd(page,num));
    		params.put("tagId", request.getParams().getType());
    		newss = newsService.find(params);
    		
    		Tag tag = null;
    		if(newss != null) {
    			for(i = 0 ; i < newss.size() ; i++) {
    				news = newss.get(i);
    				data = new ApiGetNewsListResponseModelList();
	    	    		data.setId(String.valueOf(news.getId()));
//	    	    		params = new HashMap<String, Object>();
//	    	    		params.put("newsId", news.getId());
	    	    		
	    	    		tag = new Tag();
	    	    		tag.setId(news.getTagId());
	    	    	    tag = tagService.find(tag).get(0);
	    	    		
	    	    		data.setType(tag.getName());
//	    	    		data.setTag(getNewsTags(newsTagService.find(params)));
	    	    		data.setTitle(news.getTitle());
	    	    		data.setTime(getStringDateTime(news.getShowTime()));
	    	    		data.setIcon(getAbsoulteImageUrl(news.getCover()));
	    	    		data.setDetail(StringUtils.delHTMLTag(news.getContent()));
	    	    		list.add(data);
    			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取资讯详情接口", notes = "获取资讯详情接口")
	@RequestMapping(value = "getNewsDetail", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetNewsDetailResponse getNewsDetail(@RequestBody ApiGetNewsDetailRequest request)  {
    		ApiGetNewsDetailResponse response=new ApiGetNewsDetailResponse();
    		ApiGetNewsDetailResponseModel body = new ApiGetNewsDetailResponseModel();
    		News news = null;
    		Map<String, Object> params = null;
    		SysConfig sysConfig = null;
    		String avatar = "";
    		String name = "";
    		Tag tag = null;
    		
    		// 数据未做校验
    		
    		params = new HashMap<String, Object>();
    		params.put("id", request.getParams().getId());
    		news = newsService.findOne(params);
    		
    		if(news != null) {
    			sysConfig = getSysConfig(SysConfig.CONFIG_OFFICAL_AVATAR);
    			if(sysConfig != null) {
    				avatar = sysConfig.getValue();
    			}
    			body.setAvatar(getAbsoulteImageUrl(avatar));
        		body.setDetail(news.getContent());
        		body.setIsSelf("1");
        		sysConfig = getSysConfig(SysConfig.CONFIG_OFFICAL_NAME);
    			if(sysConfig != null) {
    				name = sysConfig.getValue();
    			}
        		body.setName(name);
        		body.setTime(getStringDateTime(news.getCreateTime()));
        		body.setTitle(news.getTitle());
        		params = new HashMap<String, Object>();
        		params.put("newsId", request.getParams().getId());
        		
        		tag = new Tag();
	    		tag.setId(news.getTagId());
        		body.setType(tagService.find(tag).get(0).getName());
    		} else {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ID_NOT_EXIST);
    			return response;
    		}
    		
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取异业联盟分类接口", notes = "获取异业联盟分类接口")
	@RequestMapping(value = "getShopType", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetShopTypeResponse getShopType(@RequestBody ApiGetShopTypeRequest request)  {
    		ApiGetShopTypeResponse response=new ApiGetShopTypeResponse();
    		ApiGetShopTypeResponseModel body = new ApiGetShopTypeResponseModel();
    		List<ApiGetShopTypeResponseModelList> list = new ArrayList<ApiGetShopTypeResponseModelList>();
    		ApiGetShopTypeResponseModelList data = null;
    		List<ShopType> shopTypes = null;
    		ShopType shopType = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		
    		// 数据未做校验
    		
    		params = new HashMap<String, Object>();
    		shopTypes = shopTypeService.find(params);
    		if(shopTypes != null) {
    			for(i = 0 ; i < shopTypes.size() ; i++) {
    				shopType = shopTypes.get(i);
    				data = new ApiGetShopTypeResponseModelList();
		    		data.setId(String.valueOf(shopType.getId()));
		    		data.setName(shopType.getName());
		    		list.add(data);
    			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取异业联盟列表接口", notes = "获取异业联盟列表接口")
	@RequestMapping(value = "getShopList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetShopListResponse getShopList(@RequestBody ApiGetShopListRequest request)  {
    		ApiGetShopListResponse response=new ApiGetShopListResponse();
    		ApiGetShopListResponseModel body = new ApiGetShopListResponseModel();
    		List<ApiGetShopListResponseModelList> list = new ArrayList<ApiGetShopListResponseModelList>();
    		ApiGetShopListResponseModelList data = null;
    		List<Shop> shops = null;
    		ShopImage shopImage = null;
    		Map<String, Object> params = null;
    		int page = (request.getParams().getPage() != null && !request.getParams().getPage().equals("")) ? 
    				   Integer.valueOf(request.getParams().getPage()) : 1;
    		int num 	=  (request.getParams().getNum() != null && !request.getParams().getNum().equals("")) ? 
 				   Integer.valueOf(request.getParams().getNum()) : 20;
    		
    		params = new HashMap<String, Object>();
    		params.put("limitStart", getLimitStart(page,num));
    		params.put("limitEnd", getLimitEnd(page,num));
    		params.put("union", Shop.UNION_DIFF);
//    		params.put("regionId", Long.valueOf(request.getParams().getAreaid()));
    		String type = request.getParams().getType();//类型id，0表示全部
    		if (Long.valueOf(type) != 0) {
    			params.put("typeId", Long.valueOf(type));
			}
    		String sortStr = request.getParams().getSort();//筛选条件，0:距离最近，1：好评优先
    		switch (Integer.valueOf(sortStr)) {
			case 0:
				//TODO 距離排序
//				params.put("orderBy", "");//距離排序
				break;
			case 1:
				params.put("orderBy", "level desc");
				break;
			default:
				break;
			}
    		
		shops = shopService.find(params);
		if (shops != null) {
			for (Shop s : shops) {
				Area area = null;
				data = new ApiGetShopListResponseModelList();
				area = getPrevAddress(s.getRegionId());
				data.setId(String.valueOf(s.getId()));
				if (area != null) {
					data.setAddress(area.getAddress() + s.getAddress());
				} else {
					data.setAddress(s.getAddress());
				}

				data.setDistance("200");
				params = new HashMap<String, Object>();
				params.put("shopId", s.getId());
				shopImage = shopImageService.findOne(params);
				if (shopImage != null) {
					data.setIcon(this.getAbsoulteImageUrl(shopImage.getImage()));
				} else {
					data.setIcon("");
				}
				data.setIsSelf(String.valueOf(s.getIsOfficial() == 1 ? "1" : "0"));
				data.setLevel(String.valueOf(s.getLevel()));
				data.setTitle(s.getName());
				list.add(data);
			}
		}

		body.setList(list);
		response.setBody(body);
		return response;
	}
    
    @SuppressWarnings("deprecation")
	@IgnoreAuth
    @ApiOperation(value = "      获取商家详情接口", notes = "获取商家详情接口")
	@RequestMapping(value = "getShopDetail", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetShopDetailResponse getShopDetail(@RequestBody ApiGetShopDetailRequest request)  {
    		ApiGetShopDetailResponse response=new ApiGetShopDetailResponse();
    		ApiGetShopDetailResponseModel body = new ApiGetShopDetailResponseModel();
    		Shop shop = null;
    		Map<String, Object> params = null;
    		List<ShopImage> shopImages = null;
    		List<ShopAptitude> shopAptitudes = null;
    		ShopType shopType = null;
    		
    		// 数据未做校验
    		
    		params = new HashMap<String, Object>();
    		params.put("id", request.getParams().getId());
    		shop = shopService.findOne(params);
    		
    		if(shop != null) {
    			Area area = getPrevAddress(shop.getRegionId());
    			body.setId(String.valueOf(shop.getId()));
        		if(area != null) {
        			body.setAddress(area.getAddress() + shop.getAddress());
	    		} else {
	    			body.setAddress(shop.getAddress());
	    		}
        		body.setDetail(shop.getIntroduce());
        		params = new HashMap<String, Object>();
        		params.put("shopId", shop.getId());
        		shopImages = shopImageService.find(params);
        		body.setIcon(getMultiImageUrls1(shopImages));
        		body.setName(shop.getName());
        		body.setPhone(shop.getPhone());
        		params = new HashMap<String, Object>();
        		params.put("shopId", shop.getId());
        		shopAptitudes = shopAptitudeService.find(params);
        		body.setQualifications(getMultiImageUrls2(shopAptitudes));
        		body.setTime(String.format("%02d:%02d - %02d:%02d", 
        								   shop.getOpenStartTime().getHours(),
        								   shop.getOpenStartTime().getMinutes(),
        								   shop.getOpenEndTime().getHours(),
        								   shop.getOpenEndTime().getMinutes()));
        		params = new HashMap<String, Object>();
        		params.put("id", shop.getTypeId());
        		shopType = shopTypeService.findOne(params);
        		if(shopType != null) {
        			body.setTypeStr(shopType.getName());
        		} else {
        			body.setTypeStr("");
        		}
    		} else {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ID_NOT_EXIST);
    			return response;
    		}
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "举报商家接口", notes = "举报商家接口")
	@RequestMapping(value = "reportShop", method = RequestMethod.POST)
	@ResponseBody
	public ApiReportShopResponse reposrtShop(@RequestBody ApiReportShopRequest request)  {
    		ApiReportShopResponse response=new ApiReportShopResponse();
    		ShopReport shopReport = new ShopReport();
    		
    		// 数据未做校验
    		
    		shopReport.setUserId(Long.parseLong(request.getParams().getUserid()));
    		shopReport.setShopId(Long.parseLong(request.getParams().getId()));
    		shopReport.setReportTime(new Timestamp((new java.util.Date()).getTime()));
    		shopReport.setContent("");
    		
    		if(!shopReportService.insert(shopReport)) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_SYS_BUSY_MSG);
    			return response;
    		}
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取商品分类接口", notes = "获取商品分类接口")
	@RequestMapping(value = "getGoodsType", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetGoodsTypeResponse getGoodsType(@RequestBody ApiGetGoodsTypeRequest request)  {
    		ApiGetGoodsTypeResponse response=new ApiGetGoodsTypeResponse();
    		ApiGetGoodsTypeResponseModel body = new ApiGetGoodsTypeResponseModel();
    		List<ApiGetGoodsTypeResponseModelList> list = new ArrayList<ApiGetGoodsTypeResponseModelList>();
    		ApiGetGoodsTypeResponseModelList data = null;
    		List<GoodsCategory> goodsCategorys = null;
    		GoodsCategory goodsCategory = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		
    		params = new HashMap<String, Object>();
    		
    		if(request.getParams().getType() != null && !request.getParams().getType().equals("")) {
    			if(request.getParams().getType().equals("3"))
    				params.put("type", 4);
    			else
    				params.put("type", request.getParams().getType());
    		}
    		
    		goodsCategorys = goodsCategoryService.find(params);
    		if(goodsCategorys != null) {
    			for(i = 0 ; i < goodsCategorys.size() ; i++) {
    				goodsCategory = goodsCategorys.get(i);
    				data = new ApiGetGoodsTypeResponseModelList();
	    	    		data.setId(String.valueOf(goodsCategory.getId()));
	    	    		data.setName(goodsCategory.getName());
	    	    		list.add(data);
    			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取商品列表接口", notes = "获取商品列表接口")
	@RequestMapping(value = "getGoodsList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetGoodsListResponse getGoodsList(@RequestBody ApiGetGoodsListRequest request)  {
    		ApiGetGoodsListResponse response=new ApiGetGoodsListResponse();
    		ApiGetGoodsListResponseModel body = new ApiGetGoodsListResponseModel();
    		List<ApiGetGoodsListResponseModelList> list = new ArrayList<ApiGetGoodsListResponseModelList>();
    		ApiGetGoodsListResponseModelList data = null;
    		List<Goods> goodss = null;
    		GoodsImage goodsImage = null;
    		Map<String, Object> params = null;
    		int page = (request.getParams().getPage() != null && !request.getParams().getPage().equals("")) ? 
 				   Integer.valueOf(request.getParams().getPage()) : 1;
 		int num 	=  (request.getParams().getNum() != null && !request.getParams().getNum().equals("")) ? 
				   Integer.valueOf(request.getParams().getNum()) : 20;
				   
    		params = new HashMap<String, Object>();
    		params.put("limitStart", getLimitStart(page,num));
    		params.put("limitEnd", getLimitEnd(page,num));
    		
    		//商品种类，0:全部（默认）、1:鸿豆商品、2:积分商品、3:返利商品
    		String kindStr = request.getParams().getKind();
    		int kind = Integer.valueOf(kindStr);
    		if (kind != 0) {
    			if(kind == 3)
    				kind = 4;
    			params.put("type", kind);
		}
    		
    		//sort 筛选条件，0:销量最高，1：好评优先、2：价格最低、3：价格最高
    		String sortStr = request.getParams().getSort();
    		int sort = Integer.valueOf(sortStr);
    		switch (sort) {
			case 0:
				params.put("orderBy", "GOODS.inventory - GOODS.remain_inventory desc");
				break;
			case 1:
				params.put("orderBy", "GOODS.review desc");
				break;
			case 2:
				params.put("orderBy", "GOODS.market_price asc");
				break;
			case 3:
				params.put("orderBy", "GOODS.market_price desc");
				break;
			default:
				break;
		}
    		
    		String typeStr = request.getParams().getType();//type 商品分类id，0表示全部
    		long type = Long.valueOf(typeStr);
    		if (type !=0) {
    			params.put("categoryId", type);
		}
    		params.put("isTravelGoods", 0);		// 掉旅游商品
    		params.put("status", 1);				// 销售中的商品
    		
    		goodss = goodsService.find(params);  
    		
    		if(goodss != null && goodss.size() > 0) {
    			for (Goods g : goodss) {
    				data = new ApiGetGoodsListResponseModelList();
    				data.setId(String.valueOf(g.getId()));
    				data.setCount(String.valueOf(g.getInventory()-g.getRemainInventory()));//銷量
    				params = new HashMap<String, Object>();
    				params.put("goodsId", g.getId());
    				goodsImage = goodsImageService.findOne(params);
    				if(goodsImage != null) {
    					data.setIcon(this.getAbsoulteImageUrl(goodsImage.getImage()));
    				} else {
    					data.setIcon("");
    				}
    				if(g.getType() == 4) {
    					data.setKind("3");
    				} else {
    					data.setKind(String.valueOf(g.getType()));
    				}
    				data.setLevel(String.valueOf(g.getReview()));
    				data.setPrice(String.valueOf(g.getPrice()));
    				data.setTitle(g.getName());
    				data.setIsSale(g.getIsSpecialPrice()+"");
    				list.add(data);
			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取商品详情接口", notes = "获取商品详情接口")
	@RequestMapping(value = "getGoodsDetail", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetGoodsDetailResponse getGoodsDetail(@RequestBody ApiGetGoodsDetailRequest request)  {
    		ApiGetGoodsDetailResponse response=new ApiGetGoodsDetailResponse();
    		ApiGetGoodsDetailResponseModel body = new ApiGetGoodsDetailResponseModel();
    		ApiGetGoodsDetailResponseModelPropertyList property = null;
    		List<ApiGetGoodsDetailResponseModelPropertyList> propertyList = new ArrayList<ApiGetGoodsDetailResponseModelPropertyList>();
    		ApiGetGoodsDetailResponseModelStyleList feature = null;
    		List<ApiGetGoodsDetailResponseModelStyleList> featureList = new ArrayList<ApiGetGoodsDetailResponseModelStyleList>();
    		ApiGetGoodsDetailResponseModelStyleListValue featureValue = null;
    		List<ApiGetGoodsDetailResponseModelStyleListValue> featureValueList = null;
    		Goods goods = null;
    		List<GoodsImage> goodsImages = null;
    		Map<String, Object> params = null;
    		List<GoodsProperty> goodsPropertys = null;
    		List<GoodsFeature> goodsFeatures = null;
    		GoodsCategoryProperty goodsCategoryProperty = null;
    		GoodsCategoryFeature goodsCategoryFeature = null;
    		GoodsCategoryFeatureValue goodsCategoryFeatureValue = null;
    		
    		params = new HashMap<String, Object>();
    		params.put("id", request.getParams().getId());
    		goods = goodsService.findOne(params);
    		
    		if(goods != null) {
    			body.setId(String.valueOf(goods.getId()));
        		body.setCount(String.valueOf(getGoodsOrderCount(goods.getId())));
        		params = new HashMap<String, Object>();
	    		params.put("goodsId", goods.getId());
	    		goodsImages = goodsImageService.find(params);
        		body.setIcon(getMultiImageUrls3(goodsImages));
        		body.setPrice(String.valueOf(getGoodsPrice(goods)));
        		body.setTitle(goods.getName());
        		body.setDetail(goods.getDetail());
        		body.setInventory(String.valueOf(goods.getInventory()));
        		body.setOriPrice(String.valueOf(goods.getMarketPrice()));
        		body.setReview(String.valueOf(goods.getReview()));
        		params = new HashMap<String, Object>();
        		params.put("goodsId", request.getParams().getId());
        		goodsPropertys = goodsPropertyService.find(params);
        		if(goodsPropertys != null && goodsPropertys.size() > 0) {
        			body.setIsHaveProperty("1");
        			for (GoodsProperty p : goodsPropertys) { 
        				property = new ApiGetGoodsDetailResponseModelPropertyList();
        				params = new HashMap<String, Object>();
                		params.put("id", p.getCategoryPropertyId());
                		goodsCategoryProperty = goodsCategoryPropertyService.findOne(params);
                		if(goodsCategoryProperty != null) {
                			property.setName(goodsCategoryProperty.getName());
            				property.setValue(p.getValue());
            				propertyList.add(property);
                		}
        			}
        		} else {
        			body.setIsHaveProperty("0");
        		}
        		params = new HashMap<String, Object>();
        		params.put("goodsId", request.getParams().getId());
        		goodsFeatures = goodsFeatureService.find(params);
        		if(goodsFeatures != null && goodsFeatures.size() > 0) {
        			body.setIsHaveStyle("1");
        			for (GoodsFeature f : goodsFeatures) { 
        				feature = new ApiGetGoodsDetailResponseModelStyleList();
        				params = new HashMap<String, Object>();
                		params.put("id", f.getCategoryFeatureId());
                		goodsCategoryFeature = goodsCategoryFeatureService.findOne(params);
                		if(goodsCategoryFeature != null) {
                			feature.setId(String.valueOf(f.getId()));
                			feature.setName(goodsCategoryFeature.getName());
                			featureValueList = new ArrayList<ApiGetGoodsDetailResponseModelStyleListValue>();
                			if(f.getValue() != null && f.getValue().length() > 0) {
                				String[] strFeatureIds = f.getValue().split(",");
                    			for(int i = 0 ; i < strFeatureIds.length ; i++) {
                    				params = new HashMap<String, Object>();
                    				params.put("id", strFeatureIds[i]);
                    				goodsCategoryFeatureValue = goodsCategoryFeatureValueService.findOne(params);
                    				if(goodsCategoryFeatureValue != null) {
                    					featureValue = new ApiGetGoodsDetailResponseModelStyleListValue();
                        				featureValue.setId(strFeatureIds[i]);
                        				featureValue.setName(goodsCategoryFeatureValue.getName());
                        				featureValueList.add(featureValue);
                    				}
                    			}
                    			feature.setValueList(featureValueList);
                			}
                		}
                		featureList.add(feature);
        			}
        		} else {
        			body.setIsHaveStyle("0");
        		}
        		
        		if(goods.getType() == 4) {
        			body.setKind("3");
        		} else {
        			body.setKind(String.valueOf(goods.getType()));
        		}
        		
        		body.setPropertyList(propertyList);
        		body.setStyleList(featureList);
    		} else {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ID_NOT_EXIST);
    			return response;
    		}
    		
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "商品规格获取商品信息接口", notes = "商品规格获取商品信息接口")
	@RequestMapping(value = "getGoodsDetailByFeature", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetGoodsDetailByFeatureResponse getGoodsDetailByFeature(@RequestBody ApiGetGoodsDetailByFeatureRequest request)  {
    		ApiGetGoodsDetailByFeatureResponse response=new ApiGetGoodsDetailByFeatureResponse();
    		ApiGetGoodsDetailByFeatureResponseModel body = new ApiGetGoodsDetailByFeatureResponseModel();
    		Goods goods = null;
    		Map<String, Object> params = null;
    		ArrayList<String> featureValues = request.getParams().getFeature();
    		int i = 0;
    		int j = 0;
    		String featureValue = "";
    		String featuresKey = "";
    		GoodsInventory goodsInventory = null;
    		GoodsFeatureImage goodsFeatureImage = null;
    		GoodsImage goodsImage = null;
    		
    		params = new HashMap<String, Object>();
    		params.put("id", request.getParams().getId());
    		goods = goodsService.findOne(params);
    		if(goods == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ID_NOT_EXIST);
    			return response;
    		}
    		if(featureValues == null || featureValues.size() <= 0) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ILLEGAL_OP);
    			return response;
    		}
    		featuresKey = "[";
    		for(i = 0 ; i < featureValues.size() ; i++) {
    			featureValue = featureValues.get(i);
    			if(i != 0) {
    				featuresKey += ",";
    			}
    			featuresKey += "\"";
    			featuresKey += featureValue;
    			featuresKey += "\"";
    		}
    		featuresKey += "]";
    		params = new HashMap<String, Object>();
    		params.put("features", featuresKey);
    		params.put("goodsId", goods.getId());
    		goodsInventory = goodsInventoryService.findOne(params);
    		if(goodsInventory == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ILLEGAL_OP);
    			return response;
    		}
    		params = new HashMap<String, Object>();
    		params.put("goodsFeatureId", featuresKey);
    		params.put("goodsId", goods.getId());
    		goodsFeatureImage = goodsFeatureImageService.findOne(params);
    		
    		body.setCount(String.valueOf(goodsInventory.getSelled()));
    		if(goodsFeatureImage != null) {
    			body.setIcon(this.getAbsoulteImageUrl(goodsFeatureImage.getImage()));
    		} else {
    			params = new HashMap<String, Object>();
    			params.put("goodsId", goods.getId());
    			goodsImage = goodsImageService.findOne(params);
    			if(goodsImage != null) {
    				body.setIcon(this.getAbsoulteImageUrl(goodsImage.getImage()));
    			} else {
    				body.setIcon("");
    			}
    		}
    			
    		body.setInventory(String.valueOf(goodsInventory.getRemainInventory()));
    		if(GoodsInventory.PRICE_TYPE_BALANCE == goodsInventory.getPricetype()) {
    			body.setPrice(String.valueOf(goodsInventory.getPricebalance()));
    		} else if(GoodsInventory.PRICE_TYPE_POINTS == goodsInventory.getPricetype()) {
    			body.setPrice(String.valueOf(goodsInventory.getPricepoints()));
    		} else {
    			body.setPrice("");
    		}
    		
    		
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取活动列表接口", notes = "获取活动列表接口")
	@RequestMapping(value = "getActivityList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetActivityListResponse getActivityList(@RequestBody ApiGetActivityListRequest request)  {
    		ApiGetActivityListResponse response=new ApiGetActivityListResponse();
    		ApiGetActivityListResponseModel body = new ApiGetActivityListResponseModel();
    		List<ApiGetActivityListResponseModelList> list = new ArrayList<ApiGetActivityListResponseModelList>();
    		ApiGetActivityListResponseModelList data = null;
    		
    		Activity activity = new Activity();
    		
    		activity.setPageSize(Integer.valueOf(request.getParams().getNum()));
    		activity.setPageIndex(Integer.valueOf(request.getParams().getPage()));
    		//类型， 0：全部（默认）、1：门店活动、2：合作商家活动
    		int type = Integer.valueOf(request.getParams().getType());
    		//状态：0：全部（默认）、1：未开始、2：进行中、3：已结束
    		int status = Integer.valueOf(request.getParams().getStatus());
    		//费用：0:全部（默认）、1：免费、2：付费
    		int fee = Integer.valueOf(request.getParams().getFee());
    		Map<String, Object> params = new HashMap<String, Object>();
    		
    		updateActivityStatus();
    		
    		switch (type) {
			case 0://全部（默认）
				break;
			case 1://1：门店活动
				activity.setType(1);
				break;
			case 2://2：合作商家活动
				activity.setType(2);
				break;
			default://全部（默认）
				break;
			}
    		
    		switch (status) {
    		case 0://全部（默认）
    			break;
    		case 1://1：未开始
    			activity.setStatus(1);
    			break;
    		case 2://2：进行中
    			activity.setStatus(2);
    			break;
    		case 3://3：已结束
    			activity.setStatus(3);
    			break;
    		default://全部（默认）
    			break;
    		}
    		
    		if (fee == 1) {//免费
    			activity.setPrice(0F);
    			activity.setExistFlag(0);
    			List<Activity> listActivityResult = activityService.find(activity);
    			for (Activity activity2 : listActivityResult) {
    				data = new ApiGetActivityListResponseModelList();
    				data.setIcon(activity2.getCoverImage());
    				data.setTitle(activity2.getTitle());
    				data.setTypeStr(getActivityTypeStr(activity2.getType()));
    				data.setPrice(activity2.getPrice()+"");
    				data.setStartTime(""+activity2.getStartTime());
    				data.setEndTime(activity2.getEndTime()+"");
    				data.setId(activity2.getId()+"");
    				data.setAddress(activity2.getAddrDetail());
    				data.setStatus(activity2.getStatus()+"");
    				
    				ActivityEnroll activityEbnroll = new ActivityEnroll();
    				activityEbnroll.setActivityId(activity2.getId());
    				List<ActivityEnroll> listActivityEnroll = activityEnrollService.find(activityEbnroll);
    				int enrollNum = listActivityEnroll.size();
    				int i = activity2.getRestrictNum() - enrollNum;
    				data.setCount(i+"");//剩余名额
    				data.setIsFee(1+"");//是否免费，1：免费
    				list.add(data);
    			}
		}else if (fee == 2) {//付费
			activity.setExistFlag(0);
			List<Activity> listActivityResult = activityService.find(activity);
    			for (Activity activity2 : listActivityResult) {
    				if (activity2.getPrice() != 0) {
    					data = new ApiGetActivityListResponseModelList();
    					data.setIcon(activity2.getCoverImage());
    					data.setTitle(activity2.getTitle());
    					data.setTypeStr(getActivityTypeStr(activity2.getType()));
    					data.setPrice(activity2.getPrice()+"");
    					data.setStartTime(""+activity2.getStartTime());
    					data.setEndTime(activity2.getEndTime()+"");
    					data.setId(activity2.getId()+"");
    					data.setAddress(activity2.getAddrDetail());
    					data.setStatus(activity2.getStatus()+"");
    					
        				ActivityEnroll activityEbnroll = new ActivityEnroll();
        				activityEbnroll.setActivityId(activity2.getId());
        				List<ActivityEnroll> listActivityEnroll = activityEnrollService.find(activityEbnroll);
        				int enrollNum = listActivityEnroll.size();
        				int i = activity2.getRestrictNum() - enrollNum;
        				data.setCount(i+"");//剩余名额
    					data.setIsFee(0+"");//是否免费，1：免费
    					list.add(data);
				}
    			}
		}else {//全部
			activity.setExistFlag(0);
			List<Activity> listActivityResult = activityService.find(activity);
    			for (Activity activity2 : listActivityResult) {
    				data = new ApiGetActivityListResponseModelList();
    				data.setIcon(activity2.getCoverImage());
    				data.setTitle(activity2.getTitle());
    				data.setTypeStr(getActivityTypeStr(activity2.getType()));
    				data.setPrice(activity2.getPrice()+"");
    				data.setStartTime(""+activity2.getStartTime());
    				data.setEndTime(activity2.getEndTime()+"");
    				data.setId(activity2.getId()+"");
    				data.setAddress(activity2.getAddrDetail());
    				data.setStatus(activity2.getStatus()+"");
    				
    				ActivityEnroll activityEbnroll = new ActivityEnroll();
    				activityEbnroll.setActivityId(activity2.getId());
    				List<ActivityEnroll> listActivityEnroll = activityEnrollService.find(activityEbnroll);
    				int enrollNum = listActivityEnroll.size();
    				int i = activity2.getRestrictNum() - enrollNum;
    				data.setCount(i+"");//剩余名额
    				if(activity2.getPrice() > 0.0f)
    					data.setIsFee(0+"");
    				else
    					data.setIsFee(1+"");
    				list.add(data);
    			}
		}
    		body.setList(list);
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取活动详情接口", notes = "获取活动详情接口")
	@RequestMapping(value = "getActivityDetail", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetActivityDetailResponse getActivityDetail(@RequestBody ApiGetActivityDetailRequest request)  {
    		ApiGetActivityDetailResponse response=new ApiGetActivityDetailResponse();
    		ApiGetActivityDetailResponseModel data = new ApiGetActivityDetailResponseModel();
    		Activity activity = null;
    		Map<String, Object> params = null;
    		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
    		
    		// 未做数据有效性检查
    		
    		params = new HashMap<String, Object>();
    		params.put("id", request.getParams().getId());
    		activity = activityService.findOne(params);
    		
    		if(activity != null) {
    			params = new HashMap<String, Object>();
    			params.put("activityId", activity.getId());
    			data.setCount(String.valueOf(activityEnrollService.count(params)));
    			data.setIcon(getAbsoulteImageUrl(activity.getCoverImage()));
    			data.setPrice(String.valueOf(activity.getPrice()));
	    		data.setTitle(activity.getTitle());
        		Area area = this.getPrevAddress(activity.getRegionId());
	    		if(area != null) {
	    			data.setAddress(area.getAddress() + activity.getAddrDetail());
	    		} else {
	    			data.setAddress(activity.getAddrDetail());
	    		}
	    		data.setEndTime(this.getStringDateTime(activity.getEndTime()));
	    		data.setStartTime(this.getStringDateTime(activity.getStartTime()));
	    		data.setStatus(String.valueOf(this.getActivityStatus(activity)));
	    		if(activity.getType() == Activity.TYPE_STORE) {
	    			data.setTypeStr("门店活动");
	    		} else if(activity.getType() == Activity.TYPE_CO_SELLER) {
	    			data.setTypeStr("合作商家活动");
	    		}
        		data.setDetail(activity.getIntroduce());
        		if(noLogin(request.getParams().getUserid())) {
        			data.setIsEnroll("0");
        		} else {
        			params = new HashMap<String, Object>();
	    			params.put("activityId", activity.getId());
	    			params.put("userId", request.getParams().getUserid());
	    			data.setIsEnroll(activityEnrollService.count(params) > 0 ? "1" : "0");
        		}
        		data.setTotal(String.valueOf(activity.getRestrictNum()));
    		}
    		
    		response.setBody(data);
    		
		return response;
	}
    
   /* @IgnoreAuth
    @ApiOperation(value = "      活动报名接口", notes = "活动报名接口")
	@RequestMapping(value = "activityEnroll", method = RequestMethod.POST)
	@ResponseBody
	public ApiActivityEnrollResponse activityEnroll(@RequestBody ApiActivityEnrollRequest request)  {
    		ApiActivityEnrollResponse response=new ApiActivityEnrollResponse();
    		ActivityEnroll activityEnroll = new ActivityEnroll();
    		User user = null;
    		Activity activity = null;
    		BalanceHistory balanceHistory = null;
    		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
    		Float changedBalance = 0.0f;
    		Float currentBalance = 0.0f;
    		
    		if(noLogin(request.getParams().getUserid())) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		if(request.getParams().getId() == null || Long.parseLong(request.getParams().getId()) <= 0) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ID_NOT_EXIST);
    			return response;
    		}
    		user = getUser(Long.parseLong(request.getParams().getUserid()));
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		activity = activityService.get(Long.parseLong(request.getParams().getId()));
    		if(activity == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ID_NOT_EXIST);
    			return response;
    		}
    		if(user.getBalance() < activity.getPrice()) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_BALANCE_NOT_ENOUGH);
    			return response;
    		}
    		
    		if(activity.getStatus() != Activity.STATUS_NO_START) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ACTIVITY_CANT_ENROLL);
    			return response;
    		}
    		
    		activityEnroll.setUserId(Long.parseLong(request.getParams().getUserid()));
    		activityEnroll.setActivityId(Long.parseLong(request.getParams().getId()));
    		activityEnroll.setEnrollTime(currentTime);
    		
    		if(!activityEnrollService.insert(activityEnroll)) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ID_NOT_EXIST);
    			return response;
    		}
    		
    		currentBalance = user.getBalance() - activity.getPrice();
    		changedBalance = activity.getPrice();
    		
    		if(changedBalance > 0.0f) {
    			user.setBalance(user.getBalance() - activity.getPrice());
        		userService.update(user);
        		balanceHistory = new BalanceHistory();
        		balanceHistory.setUserId(user.getId());
        		balanceHistory.setType(BalanceHistory.TYPE_ACTIVITY_ENROLL);
        		balanceHistory.setCurrentAmount(currentBalance);
        		balanceHistory.setChangeAmount(0-changedBalance);
        		balanceHistory.setAccountType(0);
        		balanceHistory.setOrderNo("");
        		balanceHistory.setOrderAccount("");
        		balanceHistory.setActivityId(Long.parseLong(request.getParams().getId()));
        		balanceHistory.setCreateTime(currentTime);
        		balanceHistoryService.insert(balanceHistory);
    		}
    		
    		return response;
    }*/
    
    @IgnoreAuth
	@ApiOperation(value = "获取未读消息条数", notes = "获取未读消息条数")
	@RequestMapping(value = "/getMessageCount", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Long> getMessageCount(@CurrentUserId Long userId,@RequestBody Message message) {
    	
    	long count =0;
    	message.setUserId(userId);
    	message.setIsRead(0);
    	if (userId != 0 && userId != null) {
    		count = messageService.countByEntity(message);
		}
		return new ObjectDataResponse<Long>(count);
    }
    
    @IgnoreAuth
    @ApiOperation(value = "      获取消息列表接口", notes = "获取消息列表接口")
	@RequestMapping(value = "getMessageList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetMessageListResponse getMessageList(@RequestBody ApiGetMessageListRequest request)  {
    		ApiGetMessageListResponse response=new ApiGetMessageListResponse();
    		ApiGetMessageListResponseModel body = new ApiGetMessageListResponseModel();
    		List<ApiGetMessageListResponseModelList> list = new ArrayList<ApiGetMessageListResponseModelList>();
    		ApiGetMessageListResponseModelList data = null;
    		ApiGetMessageListResponseModelSysMsgInfo sysMsgInfo = new ApiGetMessageListResponseModelSysMsgInfo();
    		List<Message> messages = null;
    		Message message = null;
    		Map<String, Object> params = null;
    		String where = "";
    		int i = 0;
    		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
    		int page = (request.getParams().getPage() != null && !request.getParams().getPage().equals("")) ? 
  				   Integer.valueOf(request.getParams().getPage()) : 1;
  		int num 	=  (request.getParams().getNum() != null && !request.getParams().getNum().equals("")) ? 
 				   Integer.valueOf(request.getParams().getNum()) : 20;
 				   
    		params = new HashMap<String, Object>();
    		if(!noLogin(request.getParams().getUserid())) {
    			where = " (user_id is null or user_id = 0 or user_id = " + request.getParams().getUserid() + ")";
    		}
    		if(!where.equals("")) {
    			where += " and";
    		}
    		where += " type = " + String.valueOf(Message.TYPE_ORDER);
    		params.put("where", where);
    		params.put("limitStart", getLimitStart(page,num));
    		params.put("limitEnd", getLimitEnd(page,num));
    		params.put("orderBy", "create_time desc");
    		//调用接口显示消息已读
    		Message message2 = new Message();
    		//已读：1
    		message2.setIsRead(1);
    		//订单消息类型：2
    		message2.setType(2);
    		messageService.update(message2);
    		messages = messageService.find(params);
    		
    		if(messages != null) {
    			for(i = 0 ; i < messages.size() ; i++) {
    				message = messages.get(i);
    				data = new ApiGetMessageListResponseModelList();
	    	    		data.setId(String.valueOf(message.getId()));
	    	    		data.setTime(this.getStringDateTime(message.getCreateTime()));
	    	    		data.setDetail(message.getContent());
	    	    		data.setTitle(message.getTitle());
	    	    		data.setOrderId(message.getOrderId());
	    	    		list.add(data);
    			}
    		}
    		
    		where = "";
    		if(!noLogin(request.getParams().getUserid())) {
    			where = " (user_id is null or user_id = 0 or user_id = " + request.getParams().getUserid() + ")";
    		}
    		if(!where.equals("")) {
    			where += " and";
    		}
    		where = "type = " + String.valueOf(Message.TYPE_SYS);
    		params.put("where", where);
    		params.put("orderBy", "create_time desc");
    		message = messageService.findOne(params);
    		if(message != null) {
    			sysMsgInfo.setDeatil(message.getContent());
    			sysMsgInfo.setTime(this.getStringDateTime(message.getCreateTime()));
    		}
    	
    		body.setList(list);
    		body.setSysMsgInfo(sysMsgInfo);
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取系统消息列表接口", notes = "获取系统消息列表接口")
	@RequestMapping(value = "getSysMsgList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetSysMsgListResponse getSysMsgList(@RequestBody ApiGetSysMsgListRequest request)  {
    		ApiGetSysMsgListResponse response=new ApiGetSysMsgListResponse();
    		ApiGetSysMsgListResponseModel body = new ApiGetSysMsgListResponseModel();
    		List<ApiGetSysMsgListResponseModelList> list = new ArrayList<ApiGetSysMsgListResponseModelList>();
    		ApiGetSysMsgListResponseModelList data = null;
    		List<Message> messages = null;
    		Message message = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		String where = "";
    		
    		params = new HashMap<String, Object>();
    		if(!noLogin(request.getParams().getUserid())) {
    			where = " (user_id is null or user_id = 0 or user_id = " + request.getParams().getUserid() + ")";
    		}
    		if(!where.equals("")) {
    			where += " and";
    		}
    		where += " type = " + String.valueOf(Message.TYPE_SYS);
    		params.put("where", where);
    		params.put("orderBy", "create_time desc");
    		//分页
    		Integer pageIndex = Integer.parseInt(request.getParams().getPage());
    		Integer size  = Integer.parseInt(request.getParams().getNum());
    		params.put("limitStart", (pageIndex-1) *size);
     	    params.put("limitEnd", size);
    		
    		//调用接口显示消息已读
    		Message message2 = new Message();
    		//已读：1
    		message2.setIsRead(1);
    		//系统消息类型：1
    		message2.setType(1);
    		messageService.update(message2);
    		messages = messageService.find(params);
    		
    		if(messages != null) {
    			for(i = 0 ; i < messages.size() ; i++) {
        			message = messages.get(i);
        			
        			data = new ApiGetSysMsgListResponseModelList();
            		data.setId(String.valueOf(message.getId()));
            		data.setIsHaveDetail("1");
            		data.setTime(this.getStringDateTime(message.getCreateTime()));
            		data.setTitle(message.getContent());
            		data.setOrderId(message.getOrderId());
            		list.add(data);
        		}
    		}
    	
    		body.setList(list);
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "删除消息接口", notes = "删除消息接口")
	@RequestMapping(value = "delMessage", method = RequestMethod.POST)
	@ResponseBody
	public ApiDelMessageResponse delMessage(@RequestBody ApiDelMessageRequest request)  {
    		ApiDelMessageResponse response = new ApiDelMessageResponse();
    		Map<String, Object> params = null;
    		User user = null;
    		Long id = 0L;
    		
    		user = isLogin(Long.parseLong(request.getParams().getUserid()));
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		if(request.getParams().getId() == null || request.getParams().getId().equals("")) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ID_NOT_EXIST);
    			return response;
    		}
    		id = Long.parseLong(request.getParams().getId());
    		
    		params = new HashMap<String, Object>();
    		params.put("id", id);
    		messageService.remove(params);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取地区列表接口", notes = "获取地区列表接口")
	@RequestMapping(value = "getArea", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetAreaResponse getArea(@RequestBody ApiGetAreaRequest request)  {
    		ApiGetAreaResponse response=new ApiGetAreaResponse();
    		ApiGetAreaResponseModel body = new ApiGetAreaResponseModel();
    		List<ApiGetAreaResponseModelList> list = new ArrayList<ApiGetAreaResponseModelList>();
    		ApiGetAreaResponseModelList data = null;
    		List<Province> provinces = null;
    		Province province = null;
    		List<City> citys = null;
    		City city = null;
    		List<Region> regions = null;
    		Region region = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		
    		// 数据未做校验
    		// 添加type代表省市区，以便区分城市和地区
    		
    		params = new HashMap<String, Object>();
    		
    		if(request.getParams().getType().equals("1")) {				// 省
    			provinces = provinceService.find(params);
    			if(provinces != null) {
    				for(i = 0 ; i < provinces.size(); i++) {
    					province = provinces.get(i);
    					data = new ApiGetAreaResponseModelList();
    					data.setId(String.valueOf(province.getId()));
    					data.setName(province.getName());
    					list.add(data);
    				}
    			}
    		} else if(request.getParams().getType().equals("2")) {		// 市
    			if(!(request.getParams().getId().equals("0") || request.getParams().getId().equals(""))) {
    				params.put("provinceId", request.getParams().getId());
    			}
    			citys = cityService.find(params);
    			if(citys != null) {
    				for(i = 0 ; i < citys.size(); i++) {
    					city = citys.get(i);
    					data = new ApiGetAreaResponseModelList();
    					data.setId(String.valueOf(city.getId()));
    					data.setName(city.getName());
    					list.add(data);
    				}
    			}
    		} else if(request.getParams().getType().equals("3")) {		// 区
    			if(!(request.getParams().getId().equals("0") || request.getParams().getId().equals(""))) {
    				params.put("cityId", request.getParams().getId());
    			}
    			regions = regionService.find(params);
    			if(regions != null) {
    				for(i = 0 ; i < regions.size(); i++) {
    					region = regions.get(i);
    					data = new ApiGetAreaResponseModelList();
    					data.setId(String.valueOf(region.getId()));
    					data.setName(region.getName());
    					list.add(data);
    				}
    			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
    		
    		return response;
    }
    
    @IgnoreAuth
    @ApiOperation(value = "      获取邀请信息接口", notes = "获取邀请信息接口")
	@RequestMapping(value = "getInviteInfo", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetInviteInfoResponse getInviteInfo(@RequestBody ApiGetInviteInfoRequest request)  {
    		ApiGetInviteInfoResponse response=new ApiGetInviteInfoResponse();
    		ApiGetInviteInfoResponseModel body = new ApiGetInviteInfoResponseModel();
    		User user = null;
    		SysConfig sysConfig = null;
    
    		// 数据未做校验
    		
    		if(noLogin(request.getParams().getUserid())) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		user = userService.get(Long.parseLong(request.getParams().getUserid()));
    		
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ID_NOT_EXIST);
    			return response;
    		}
    		
    		sysConfig = getSysConfig(SysConfig.CONFIG_INVITE_RULE);
    		if(sysConfig != null) {
    			body.setDetail(sysConfig.getValue());
    		} else {
    			body.setDetail("");
    		}
    		sysConfig = getSysConfig(SysConfig.CONFIG_INVITE_SHARE_TITLE);
    		if(sysConfig != null) {
    			body.setShareTitle(sysConfig.getValue());
    		} else {
    			body.setShareTitle("");
    		}
    		sysConfig = getSysConfig(SysConfig.CONFIG_INVITE_SHARE_ICON);
    		if(sysConfig != null) {
    			body.setShareIcon(sysConfig.getValue());
    		} else {
    			body.setShareIcon("");
    		}
    		String detail = "";
    		if(user!=null){
    			if(user.getNickname()!=null){
    				detail = user.getNickname();
    			}else{
    			    if(user.getPhone()!=null&&user.getPhone().length()==11){
    			    	String str1 =  user.getPhone().substring(0,3);
    			    	String str2 =  user.getPhone().substring(7,11);
    			    	detail = str1+"****"+str2;
    			    }
    			}		
    		}
    		sysConfig = getSysConfig(SysConfig.CONFIG_INVITE_SHARE_DETAIL);
    		if(sysConfig != null) {
    			body.setShareDetail("我是["+detail+"]"+sysConfig.getValue());
    		} else {
    			body.setShareDetail("");
    		}
    		body.setCode(user.getInviteCode());
    		
    		sysConfig = getSysConfig(SysConfig.CONFIG_SHARE_BASE_URL);
    		if(sysConfig != null) {
    			body.setShareUrl(sysConfig.getValue() + "/" + "invite.html?code=" + user.getInviteCode());
    		} else {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_GET_SHARE_URL);
    			return response;
    		}
    		
    		body.setQrCode(getAbsoulteImageUrl(user.getQrcode()));
    
    		response.setBody(body);
    		
    		return response;
    }
    
    // here
    @IgnoreAuth
    @ApiOperation(value = "      奖励记录接口", notes = "      奖励记录接口")
	@RequestMapping(value = "getAwardHistory", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetAwardHistoryResponse getAwardHistory(@RequestBody ApiGetBalanceDetailListRequest request)  {
    		ApiGetAwardHistoryResponse response=new ApiGetAwardHistoryResponse();
    		ApiGetAwardHistoryResponseModel body = new ApiGetAwardHistoryResponseModel();
    		List<ApiGetAwardHistoryResponseModelObjList> objList = new ArrayList<ApiGetAwardHistoryResponseModelObjList>();
    		ApiGetAwardHistoryResponseModelObjList objData = null;
    		List<ApiGetAwardHistoryResponseModelInviteList> inviteList = new ArrayList<ApiGetAwardHistoryResponseModelInviteList>();
    		ApiGetAwardHistoryResponseModelInviteList inviteData = null;
    		List<BalanceHistory> balanceHistorys = null;
    		Map<String, Object> params = null;
    		User user = null;
    		int i = 0;
    		int page = (request.getParams().getPage() != null && !request.getParams().getPage().equals("")) ? 
 				   Integer.valueOf(request.getParams().getPage()) : 1;
 		int num 	=  (request.getParams().getNum() != null && !request.getParams().getNum().equals("")) ? 
				   Integer.valueOf(request.getParams().getNum()) : 20;
    		
    		user = getUser(Long.parseLong(request.getParams().getUserid()));
    		if (user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
		}
    		body.setTotalIntegral(String.valueOf(user.getTotalPoints()));
    		body.setTotalPrice(String.valueOf(user.getTotalRewardBalance()));
    		
    		//objList
    		params = new HashMap<String, Object>();
    		params.put("userId", request.getParams().getUserid());
    		List<InviteHistory> listInviteHistory = inviteHistoryService.find(params);
    		if(listInviteHistory != null && listInviteHistory.size() > 0) {
    			for(i = 0 ; i < listInviteHistory.size(); i++) {
    				InviteHistory inviteHistory = listInviteHistory.get(i);
    				params = new HashMap<String, Object>();
    	    			params.put("id", inviteHistory.getInviteUserId());
    	    			User u = userService.findOne(params);
    				objData = new ApiGetAwardHistoryResponseModelObjList();
    				objData.setIcon(this.getAbsoulteImageUrl(u.getPortrait()));
    				objData.setName(u.getNickname());
    				objData.setTime(getStringDate(u.getCreateTime()));
    				params = new HashMap<String, Object>();
    				params.put("userId", u.getId());
    				if(userLoginHistoryService.count(params) > 0) {
    					objData.setStatusStr("注册登录成功");
    				} else {
    					objData.setStatusStr("注册成功，等待登录");
    				}
    				
    				objData.setUserid(String.valueOf(u.getId()));
    				objList.add(objData);
    			}
    		}
    		
    		//inviteList
    		params = new HashMap<String, Object>();
    		params.put("limitStart", getLimitStart(page,num));
    		params.put("limitEnd", getLimitEnd(page,num));
    		params.put("userId", request.getParams().getUserid());
    		balanceHistorys = null; //balanceHistoryService.findBalanceAndPoints(params);
    		
    		for(BalanceHistory bh : balanceHistorys) {
    			inviteData = new ApiGetAwardHistoryResponseModelInviteList();
    			params = new HashMap<String, Object>();
    			/*params.put("id", bh.getObjUserId());*/
    			User user1 = userService.findOne(params);
    			inviteData.setName(user1.getNickname());
    			inviteData.setIcon(getAbsoulteImageUrl(user1.getPortrait()));
    			inviteData.setTime(getStringDate(user1.getCreateTime()));
    			/*inviteData.setAward(String.valueOf(bh.getChangeAmount()));*/
    			
    			/*if(bh.getType() == PointsHistory.POINT_TYPE_INVITE) {
    				inviteData.setDetail("用户登录注册成功");
    				inviteData.setIsPrice("0");
    			} else if(bh.getType() == BalanceHistory.TYPE_SUBORDINATE_CONSUME) {
    				inviteData.setDetail("下线消费奖励");
    				inviteData.setIsPrice("1");
    			}*/
    			inviteList.add(inviteData);
    		}
    		
//    		
//    		params.put("userId", request.getParams().getUserid());
//    		List<InviteHistory> listInvite = inviteHistoryService.find(params);
//    		for (InviteHistory invite : listInvite) {
//    			params = new HashMap<String, Object>();
//				params.put("userId", invite.getUserId());
//				if(userLoginHistoryService.count(params) > 0) {//登陸成功
//					inviteData = new ApiGetAwardHistoryResponseModelInviteList();
//					
//					User inviteUser = getUser(invite.getInviteUserId());
//					inviteData.setIcon(this.getAbsoulteImageUrl(inviteUser.getPortrait()));
//					inviteData.setName(inviteUser.getNickname());
//					inviteData.setTime(invite.getInviteTime()+"");
//					float rewardMoney = inviteUser.getTotalRewardBalance();
//					if (rewardMoney > 0) {
//						inviteData.setIsPrice("1");//奖励是否是钱，1：是
//						inviteData.setAward(rewardMoney+"");
//					}else {
//						inviteData.setIsPrice("0");//奖励是否是钱，1：是
//						inviteData.setAward(inviteUser.getPoints()+"");
//					}
//					//TODO 描述
//					inviteData.setDetail("");//描述
//				}
//			}
    		
    		params = new HashMap<String, Object>();
    		params.put("inviterUserId", request.getParams().getUserid());
    		body.setTotalCount(String.valueOf(userService.count(params)));
    		body.setUserType(String.valueOf(user.getType()));
    		body.setInviteList(inviteList);
    		body.setObjList(objList);
    		response.setBody(body);
    		
    		return response;
    }
    
    /*@IgnoreAuth
    @ApiOperation(value = "      其他用户邀请明细接口", notes = "其他用户邀请明细接口")
	@RequestMapping(value = "getOtherUserInvite", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetOtherUserInviteResponse getOtherUserInvite(@RequestBody ApiGetOtherUserInviteRequest request)  {
    		ApiGetOtherUserInviteResponse response=new ApiGetOtherUserInviteResponse();
    		ApiGetOtherUserInviteResponseModel body = new ApiGetOtherUserInviteResponseModel();
    		List<ApiGetOtherUserInviteResponseModelList> list = new ArrayList<ApiGetOtherUserInviteResponseModelList>();
    		ApiGetOtherUserInviteResponseModelList data = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		Long userId = 0L;
    		List<User> users = null;
    		User user = null;
    		User otherUser = null;
    		List<BalanceHistory> balanceHistorys = null;
    		int page = (request.getParams().getPage() != null && !request.getParams().getPage().equals("")) ? 
 				   Integer.valueOf(request.getParams().getPage()) : 1;
 		int num 	=  (request.getParams().getNum() != null && !request.getParams().getNum().equals("")) ? 
				   Integer.valueOf(request.getParams().getNum()) : 20;
    		
    		if(this.noLogin(request.getParams().getUserid())) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		if(request.getParams().getId() != null)
    			userId = Long.parseLong(request.getParams().getId());
    		if(userId <= 0) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ILLEGAL_OP);
    			return response;
    		}
    		params = new HashMap<String, Object>();
    		params.put("id", userId);
    		user = userService.findOne(params);
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ILLEGAL_OP);
    			return response;
    		}
    		
    		params = new HashMap<String, Object>();
    		params.put("limitStart", getLimitStart(page,num));
    		params.put("limitEnd", getLimitEnd(page,num));
    		params.put("userId", request.getParams().getUserid());
    		params.put("objUserId", userId);
    		balanceHistorys = balanceHistoryService.findBalanceAndPoints(params);
    		
    		for(BalanceHistory bh : balanceHistorys) {
    			data = new ApiGetOtherUserInviteResponseModelList();
    			data.setName(user.getNickname());
    			data.setIcon(getAbsoulteImageUrl(user.getPortrait()));
    			data.setTime(getStringDate(user.getCreateTime()));
    			data.setAward(String.valueOf(bh.getChangeAmount()));
    			
    			if(bh.getType() == PointsHistory.POINT_TYPE_INVITE) {
    				data.setDetail("用户登录注册成功");
    				data.setIsPrice("0");
    			} else if(bh.getType() == BalanceHistory.TYPE_SUBORDINATE_CONSUME) {
    				data.setDetail("下线消费奖励");
    				data.setIsPrice("1");
    			}
    			list.add(data);
    		}
    		body.setList(list);
    		response.setBody(body);
    		
    		return response;
    }*/
    
    @IgnoreAuth
    @ApiOperation(value = "      获取余额明细列表接口", notes = "获取余额明细列表接口")
	@RequestMapping(value = "getBalanceDetailList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetBalanceDetailListResponse getBalanceDetailList(@RequestBody ApiGetBalanceDetailListRequest request)  {
    		ApiGetBalanceDetailListResponse response=new ApiGetBalanceDetailListResponse();
    		ApiGetBalanceDetailListResponseModel body = new ApiGetBalanceDetailListResponseModel();
    		List<ApiGetBalanceDetailListResponseModelList> list = new ArrayList<ApiGetBalanceDetailListResponseModelList>();
    		ApiGetBalanceDetailListResponseModelList data = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		List<BalanceHistory> balanceHistorys = null;
    		BalanceHistory balanceHistory = null;
    		
    		params = new HashMap<String, Object>();
    		params.put("userId", request.getParams().getUserid());
    		params.put("orderBy", "create_time desc");
    		Integer pageIndex = Integer.parseInt(request.getParams().getPage());
    		Integer size  = Integer.parseInt(request.getParams().getNum());
    		params.put("limitStart", (pageIndex-1) *size);
     	    params.put("limitEnd", size);
    		balanceHistorys = balanceHistoryService.find(params);
    		
    		if(balanceHistorys != null) {
    			for(i = 0 ; i < balanceHistorys.size() ; i++) {
    				balanceHistory = balanceHistorys.get(i);
    				if (balanceHistory.getType() ==1 ||balanceHistory.getType() ==2 || balanceHistory.getType() ==4 || balanceHistory.getType() ==8 || balanceHistory.getType() ==9 || balanceHistory.getType() ==12 ||  balanceHistory.getType() ==11 ||  balanceHistory.getType() ==15 || balanceHistory.getType() ==16 || balanceHistory.getType() ==17 ||  balanceHistory.getType() ==19 || balanceHistory.getType() ==20 ) {
    					data = new ApiGetBalanceDetailListResponseModelList();
    					
    					data.setId(String.valueOf(balanceHistory.getId()));
    					if(balanceHistory.getType() ==2 || balanceHistory.getType() ==4 || balanceHistory.getType() ==9 || balanceHistory.getType() ==12 || balanceHistory.getType() ==20){
    						data.setCount(String.valueOf("-" + balanceHistory.getAmount()));
    					}
    					else{
    						data.setCount(String.valueOf("+" + balanceHistory.getAmount()));
    					}
    					data.setTime(getStringDateTime(balanceHistory.getCreateTime()));
    					switch(balanceHistory.getType()) {
    					case 1 :
    						data.setTitle("充值" + balanceHistory.getAmount() + "元");
    						break;
    					case 2 :
    						data.setTitle("购买鸿福家园商品");
    						break;
    					case 4 :
    						data.setTitle("购买旅游商品");
    						break;
    					case 8 :
    						data.setTitle("系统赠送");
    						break;
    					case 9 :
    						data.setTitle("系统扣除");
    						break;
    					case 11 :
    						data.setTitle("分销提成");
    						break;
    					case 12 :
    						data.setTitle("报名活动");
    						break;
    					case 15 :
    						data.setTitle("报名活动退款");
    						break;
    					case 16 :
    						data.setTitle("购买鸿福家园商品退款");
    						break;
    					case 17 :
    						data.setTitle("购买旅游商品退款");
    						break;
    					case 18 :
    						data.setTitle("购买积分产品退还");
    						break;
    					case 19 :
    						data.setTitle("添加可提现余额");
    						break;
    					case 20 :
    						data.setTitle("减少可提现余额");
    						break;
    					case 25 :
    						data.setTitle("购买"+getNumber(balanceHistory.getUserLevel())+"星会员卡");
    						break;
    					default :
    						data.setTitle("未知");
    						break;
    					}
    					if(balanceHistory.getType() ==2 || balanceHistory.getType() ==4 || balanceHistory.getType() ==9 || balanceHistory.getType() ==12 || balanceHistory.getType() ==19){
    						//加
    						data.setType(String.valueOf(1));
    					}
    					else{
    						//减
    						data.setType(String.valueOf(2)); 
    					}
    					if(balanceHistory.getAmount()!=null){
    						list.add(data);
    					}
					}
    				
    			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取积分明细列表接口", notes = "获取积分明细列表接口")
	@RequestMapping(value = "getIntegralDetailList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetIntegralDetailListResponse getIntegralDetailList(@RequestBody ApiGetIntegralDetailListRequest request)  {
    		ApiGetIntegralDetailListResponse response=new ApiGetIntegralDetailListResponse();
    		ApiGetIntegralDetailListResponseModel body = new ApiGetIntegralDetailListResponseModel();
    		List<ApiGetIntegralDetailListResponseModelList> list = new ArrayList<ApiGetIntegralDetailListResponseModelList>();
    		ApiGetIntegralDetailListResponseModelList data = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		List<PointsHistory> pointsHistorys = null;
    		PointsHistory pointsHistory = null;
    		
    		params = new HashMap<String, Object>();
    		params.put("userId", request.getParams().getUserid());
    		Integer pageIndex = Integer.parseInt(request.getParams().getPage());
    		Integer size  = Integer.parseInt(request.getParams().getNum());
    		params.put("limitStart", (pageIndex-1) *size);
     	    params.put("limitEnd", size);
     	    params.put("orderBy", "POINTS_HISTORY.create_time desc");
    		pointsHistorys = pointsHistoryService.find(params);
    		
    		if(pointsHistorys != null) {
    			for(i = 0 ; i < pointsHistorys.size() ; i++) {
    				pointsHistory = pointsHistorys.get(i);
    				data = new ApiGetIntegralDetailListResponseModelList();
    				
    				data.setId(String.valueOf(pointsHistory.getId()));
    				if(pointsHistory.getChangePoints() > 0){
    					if (pointsHistory.getType() ==2 || pointsHistory.getType() ==8) {
    						data.setCount(String.valueOf(0-pointsHistory.getChangePoints()));
						}else {
							data.setCount(String.valueOf("+" + pointsHistory.getChangePoints()));
						}
    				}
    				else
    					data.setCount(String.valueOf(pointsHistory.getChangePoints()));
	    	    		data.setTime(getStringDateTime(pointsHistory.getCreateTime()));
	    	    		switch(pointsHistory.getType()) {
	    	    		case PointsHistory.POINT_TYPE_SIGN :
	    	    			data.setTitle("每日签到");
	    	    			break;
	    	    		case PointsHistory.POINT_TYPE_BUY :
	    	    			data.setTitle("购买商品");
	    	    			break;
	    	    		case PointsHistory.POINT_TYPE_INVITE :
	    	    			data.setTitle("邀请好友");
		    	    		break;
	    	    		case PointsHistory.POINT_TYPE_REGISTER :
	    	    			data.setTitle("注册赠送");
	    	    			break;
	    	    		case PointsHistory.POINT_TYPE_SYS_GIVE :
	    	    			data.setTitle("系统赠送");
	    	    			break;
	    	    		case PointsHistory.POINT_TYPE_SYS_DEDUCT :
	    	    			data.setTitle("系统扣除");
		    	    		break;
	    	    		case 7:
	    	    			data.setTitle("购买积分商品退分");
	    	    			break;
	    	    		case 8:
	    	    			data.setTitle("赠送积分消耗");
	    	    			break;
	    	    		case 9:
	    	    			data.setTitle("用户获取积分");
	    	    			break;
	    	    		case 10:
	    	    			data.setTitle("用户购买积分");
	    	    			break;
		    	    	default :
		    	    		data.setTitle("未知");
		    	    		break;
	    	    		}
	    	    		/*if(pointsHistory.getChangePoints() > 0)*/
	    	    			/*data.setType(String.valueOf(BalanceHistory.CHANGE_ADD));*/
	    	    		/*else
	    	    			data.setType(String.valueOf(BalanceHistory.CHANGE_REDUCE));*/
    				list.add(data);
    			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      获取提现列表接口", notes = "获取提现列表接口")
	@RequestMapping(value = "getWithdrawList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetWithdrawListResponse getWithdrawalList(@RequestBody ApiGetWithdrawListRequest request)  {
    		ApiGetWithdrawListResponse response=new ApiGetWithdrawListResponse();
    		ApiGetWithdrawListResponseModel body = new ApiGetWithdrawListResponseModel();
		List<ApiGetWithdrawListResponseModelList> list = new ArrayList<ApiGetWithdrawListResponseModelList>();
		ApiGetWithdrawListResponseModelList data = null;
		Map<String, Object> params = null;
		int i = 0;
		List<WithdrawHistory> withdrawHistorys = null;
		WithdrawHistory withdrawHistory = null;
		
		params = new HashMap<String, Object>();
		params.put("userId", request.getParams().getUserid());
		withdrawHistorys = withdrawHistoryService.find(params);
		
		if(withdrawHistorys != null) {
			for(i = 0 ; i < withdrawHistorys.size() ; i++) {
				withdrawHistory = withdrawHistorys.get(i);
				data = new ApiGetWithdrawListResponseModelList();
				
				data.setId(String.valueOf(withdrawHistory.getId()));
	    	    		data.setCount(String.valueOf(withdrawHistory.getAmount()));
	    	    		data.setTime(getStringDateTime(withdrawHistory.getCreateTime()));
	    	    		data.setStatus(String.valueOf(withdrawHistory.getStatus()));
				list.add(data);
			}
		}
		
		body.setList(list);
		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      充值下单接口", notes = "充值下单接口")
	@RequestMapping(value = "rechargeOrder", method = RequestMethod.POST)
	@ResponseBody
	public ApiRechargeOrderResponse rechargetOrder(@RequestBody ApiRechargeOrderRequest request)  {
    		ApiRechargeOrderResponse response=new ApiRechargeOrderResponse();
    		ApiRechargeOrderResponseModel body = new ApiRechargeOrderResponseModel();
    		
    		
    		int type = Integer.valueOf(request.getParams().getType());//0：苹果内购，1:支付宝，2：微信
    		String price = request.getParams().getPrice();//金额
    		
    		if (type == 1) {//支付宝
//    			AlipayConfig alipayConfig = new AlipayConfig();
//    			try {
//					String order = alipayConfig.getAlipayOrder("这是充值的订单", "充值订单", "123456789", price, "http://www.baidu.com");
//					
//					//TODO .......
//				} catch (AlipayApiException e) {
//					e.printStackTrace();
//					response.setResultMsg(e.getErrMsg());
//					return response;
//				}
    		}
    		
    		if (type ==2) {//微信
				
			}
    		
    		
    		body.setAppid("appid");
    		body.setNonceStr("nonceStr");
    		body.setOrderID("1234567664344");
    		body.setOrderString("orderString");
    		body.setPartnerID("1");
    		body.setPkg("package");
    		body.setPrepayID("2");
    		body.setSign("signsign");
    		body.setTimestamp("21345364656");
    		
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      充值金额接口", notes = "充值金额接口")
	@RequestMapping(value = "rechargePay", method = RequestMethod.POST)
	@ResponseBody
	public ApiRechargePayResponse rechargetPay(@RequestBody ApiRechargePayRequest request)  {
    		ApiRechargePayResponse response=new ApiRechargePayResponse();
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "      添加／编辑地址接口", notes = "      添加／编辑地址接口")
	@RequestMapping(value = "addAddress", method = RequestMethod.POST)
	@ResponseBody
	public ApiAddAddressResponse addAddress(@RequestBody ApiAddAddressRequest request)  {
    		ApiAddAddressResponse response=new ApiAddAddressResponse();
    		boolean isAdd = request.getParams().getId() != null && request.getParams().getId().equals("0");
    		Map<String, Object> params = null;
    		List<UserAddress> userAddresses = null;
    		UserAddress userAddress = null;
    		UserAddress userAddress1 = null;
    		int i = 0;
    		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
    		
    		if(noLogin(request.getParams().getUserid())) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		if(isAdd) {
    			userAddress = new UserAddress();
    		} else {
    			params = new HashMap<String, Object>();
    			params.put("id", request.getParams().getId());
    			userAddress = userAddressService.findOne(params);
    			if(userAddress == null) {
    				response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
        			response.setResultMsg(ApiRestfulResponse.ERROR_ID_NOT_EXIST);
        			return response;
    			}
    		}
    		userAddress.setUserId(Long.parseLong(request.getParams().getUserid()));
    		userAddress.setName(request.getParams().getName());
    		userAddress.setPhone(request.getParams().getPhone());
    		userAddress.setRegionId(Long.parseLong(request.getParams().getAreaid()));
    		userAddress.setAddress(request.getParams().getAddress());
    		userAddress.setIsDefault(Integer.parseInt(request.getParams().getIsDefault()));
    		if(request.getParams().getIsDefault() != null && request.getParams().getIsDefault().equals("1")) {
    			params = new HashMap<String, Object>();
    			params.put("userId", request.getParams().getUserid());
    			
    			userAddresses = userAddressService.find(params);
    			if(userAddresses != null) {
    				for(i = 0 ; i < userAddresses.size(); i++) {
    					userAddress1 = userAddresses.get(i);
    					userAddress1.setIsDefault(0);
    					userAddressService.update(userAddress1);
    				}
    			}
    		}
    		if(isAdd) {
    			userAddress.setCreateTime(currentTime);
    		}
    		userAddress.setUpdateTime(currentTime);
    		
    		if(isAdd) {
    			userAddressService.insert(userAddress);
    		} else {
    			userAddressService.update(userAddress);
    		}
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "获取收货地址列表接口", notes = "      获取收货地址列表接口")
	@RequestMapping(value = "getAddressList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetAddressListResponse getAddressList(@RequestBody ApiGetAddressListRequest request)  {
    		ApiGetAddressListResponse response=new ApiGetAddressListResponse();
    		ApiGetAddressListResponseModel body = new ApiGetAddressListResponseModel();
    		List<ApiGetAddressListResponseModelList> list = new ArrayList<ApiGetAddressListResponseModelList>();
    		ApiGetAddressListResponseModelList data = null;
    		Map<String, Object> params = null;
    		List<UserAddress> userAddresses = null;
    		UserAddress userAddress = null;
    		int i = 0;
    		
    		if(noLogin(request.getParams().getUserid())) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		params = new HashMap<String, Object>();
    		params.put("userId", request.getParams().getUserid());
    		userAddresses = userAddressService.find(params);
    		
    		if(userAddresses != null) {
    			for(i = 0 ; i < userAddresses.size() ; i++) {
    				userAddress = userAddresses.get(i);
    				Area area = getPrevAddress(userAddress.getRegionId());
    				data = new ApiGetAddressListResponseModelList();
	    	    		data.setId(String.valueOf(userAddress.getId()));
	    	    		if(area != null)
	    	    			data.setAreaDetail(area.getAddress());
	    	    		else
	    	    			data.setAreaDetail("");
	    	    		data.setAddress(userAddress.getAddress());
	    	    		data.setAreaid(String.valueOf(userAddress.getRegionId()));
	    	    		data.setIsDefault(String.valueOf(userAddress.getIsDefault()));
	    	    		data.setName(userAddress.getName());
	    	    		data.setPhone(userAddress.getPhone());
	    	    		list.add(data);
    			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "获取默认地址接口", notes = "      获取默认地址接口")
	@RequestMapping(value = "getDefaultAddress", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetDefaultAddressResponse getDefaultAddress(@RequestBody ApiGetDefaultAddressRequest request)  {
    		ApiGetDefaultAddressResponse response=new ApiGetDefaultAddressResponse();
    		ApiGetDefaultAddressResponseModel body = new ApiGetDefaultAddressResponseModel();
    		Map<String, Object> params = null;
    		UserAddress userAddress = null;
    		
    		if(noLogin(request.getParams().getUserid())) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		params = new HashMap<String, Object>();
    		params.put("userId", request.getParams().getUserid());
    		params.put("isDefault", 1);
    		userAddress = userAddressService.findOne(params);
    		if(userAddress != null) {
    			body.setAddress(userAddress.getAddress());
    			body.setId(String.valueOf(userAddress.getId()));
    			body.setName(userAddress.getName());
    			body.setPhone(userAddress.getPhone());
    			Area area = getPrevAddress(userAddress.getRegionId());
    			if(area != null) {
    				body.setAreaDetail(area.getAddress());
    			} else {
    				body.setAreaDetail("");
    			}
    		}else {//默认地址
    			body.setId("0");
    			body.setAddress("");
    			body.setName("");
    			body.setPhone("");
    			body.setAreaDetail("");
		}
    		
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "地址操作接口", notes = "      地址操作接口")
	@RequestMapping(value = "addressHandle", method = RequestMethod.POST)
	@ResponseBody
	public ApiAddressHandleResponse addressHandle(@RequestBody ApiAddressHandleRequest request)  {
    		ApiAddressHandleResponse response=new ApiAddressHandleResponse();
    		Map<String, Object> params = null;
    		UserAddress userAddress = null;
    		List<UserAddress> userAddresses = null;
    		UserAddress userAddress1 = null;
    		int i = 0;
    		
    		if(noLogin(request.getParams().getUserid())) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		params = new HashMap<String, Object>();
    		params.put("userId", request.getParams().getUserid());
    		params.put("id", request.getParams().getId());
    		userAddress = userAddressService.findOne(params);
    		
    		if(userAddress == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_ID_NOT_EXIST);
    			return response;
    		}
    		
    		if(Integer.parseInt(request.getParams().getType()) == ApiAddressHandleRequest.OP_SET_DEFAULT) {
    			params = new HashMap<String, Object>();
        		params.put("userId", request.getParams().getUserid());
        		userAddresses = userAddressService.find(params);
        		if(userAddresses != null) {
        			for(i = 0 ; i < userAddresses.size(); i++) {
        				userAddress1 = userAddresses.get(i);
        				userAddress1.setIsDefault(0);
        				userAddressService.update(userAddress1);
        			}
        		}
    			userAddress.setIsDefault(1);
    			userAddressService.update(userAddress);
    		} else if(Integer.parseInt(request.getParams().getType()) == ApiAddressHandleRequest.OP_DELETE) {
    			userAddressService.remove(userAddress);
    		}
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "获取我的积分信息接口", notes = "获取我的积分信息接口")
	@RequestMapping(value = "getMyIntegral", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetMyIntegralResponse getMyIntegral(@RequestBody ApiGetMyIntegralRequest request)  {
    		ApiGetMyIntegralResponse response=new ApiGetMyIntegralResponse();
    		ApiGetMyIntegralResponseModel body = new ApiGetMyIntegralResponseModel();
    		List<ApiGetMyIntegralResponseModelList> list = new ArrayList<ApiGetMyIntegralResponseModelList>();
    		ApiGetMyIntegralResponseModelList data = null;
    		User user = null;
    		Map<String, Object> params = null;
    		PointsHistory points = null;
    		int isSign = 0;
    		Timestamp currentDateTime = new Timestamp((new java.util.Date()).getTime());
    		Timestamp currentTime = new Timestamp((new java.util.Date().getTime()));
    		List<Goods> goodss = null;
    		Goods goods = null;
    		GoodsImage goodsImage = null;
    		int continuationSignDays = 1;
    		int i = 0;
    		
    		user = isLogin(Long.parseLong(request.getParams().getUserid()));
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		params = new HashMap<String, Object>();
    		params.put("type", PointsHistory.POINT_TYPE_SIGN);
    		params.put("orderBy", "create_time desc");
    		params.put("userId", request.getParams().getUserid());
    		points = pointsHistoryService.findOne(params);
    		if(points != null) {
    			if(currentTime!=null&&points.getCreateTime()!=null){
    				System.out.println(currentTime.getTime());
    				
    				//得到long类型当前时间
    				long l = System.currentTimeMillis();
    				//new日期对象
    				Date date = new Date(l);
    				//转换提日期输出格式
    				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    				System.out.println(dateFormat.format(date));
//    				Timestamp ts = new Timestamp(dateFormat.format(date));
    				if(dateFormat.format(date).toString().substring(0,10 ).equals(points.getCreateTime().toString().substring(0,10))) {
    					//已签到
        				isSign = 1;
        			} else {
        				isSign = 0;
        			}
    			}else{
    				isSign = 0;
    			}
    			
    		}
    		
    	/*	params = new HashMap<String, Object>();
    		params.put("type", Goods.TYPE_POINTS);
    		params.put("isTravelGoods", 0);*/
    		
    		Goods g=new Goods();
    		g.setType(Goods.TYPE_POINTS);
    		g.setIsTravelGoods(0);
    		goodss = goodsdao.findAllGoods2(g);
    		if(goodss != null) {
    			for(i = 0 ; i < goodss.size(); i++) {
    				goods = goodss.get(i);
        			data = new ApiGetMyIntegralResponseModelList();
            		data.setId(String.valueOf(goods.getId()));
            		data.setIntegral(String.valueOf(getGoodsPrice(goods).intValue()));
            		data.setTitle(goods.getName());
            		params = new HashMap<String, Object>();
            		params.put("goodsId", goods.getId());
            		goodsImage = goodsImageService.findOne(params);
            		if(goodsImage != null) {
            			data.setIcon(getAbsoulteImageUrl(goodsImage.getImage()));
            		} else {
            			data.setIcon("");
            		}
            		list.add(data);
    			}
    		}
    		
    		body.setIntegral(String.valueOf(user.getPoints()));
    		body.setIsSign(String.valueOf(isSign));
    		body.setList(list);
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "签到接口", notes = "签到接口")
	@RequestMapping(value = "sign", method = RequestMethod.POST)
	@ResponseBody
	public ApiSignResponse sign(@RequestBody ApiSignRequest request)  {
    		ApiSignResponse response = new ApiSignResponse();
    		ApiSignResponseModel body = new ApiSignResponseModel();
    		User user = null;
    		SysConfig sysConfig = null;
    		int signPoints = 5;
    		SignHistory signHistory = null;
    		PointsHistory pointsHistory = null;
    		List<SignHistory> signHistorys = null;
    		Timestamp currentTime = new Timestamp((new java.util.Date().getTime()));
    		Map<String, Object> params = null;
    		int continuationSignDays = 1;
    		int i = 0;
    		
    		user = isLogin(Long.parseLong(request.getParams().getUserid()));
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		params = new HashMap<String, Object>();
    		params.put("userId", user.getId());
    		params.put("orderBy", "sign_time desc");
    		signHistorys = signHistoryService.find(params);
    		if(signHistorys != null) {
    			for(i = 0 ; i < signHistorys.size(); i++) {
    				signHistory = signHistorys.get(i);
    				if(i == 0) {
    					if(signHistory.getSignTime().toString().substring(0,10).equals(currentTime.toString().substring(0,10 ))) {
    						response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
	    		    			response.setResultMsg(ApiRestfulResponse.ERROR_SIGNED);
	    		    			return response;
    					}
    				}
//    				Timestamp ts = new Timestamp(currentTime.getTime() / 1000 - 3600 * 24 * continuationSignDays);
    				java.util.Date yesterday = new java.util.Date( (new java.util.Date()).getTime() - 86400000*continuationSignDays);
    				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    				
    				if(signHistory.getSignTime().toString().substring(0,10).equals(dateFormat.format(yesterday).toString().substring(0,10))) {
    					continuationSignDays++;
    				}
    			}
    		}
    		
    		sysConfig = getSysConfig(SysConfig.CONFIG_SIGN_POINTS);
    		if(sysConfig != null) {
    			signPoints = Integer.parseInt(sysConfig.getValue());
    		}
    		user.setPoints(user.getPoints() + signPoints);
    		userService.update(user);
    		
    		signHistory = new SignHistory();
    		signHistory.setUserId(user.getId());
    		signHistory.setSignTime(currentTime);
    		signHistory.setPoints(signPoints);
    		signHistoryService.insert(signHistory);
    		
    		// 订单编号
    		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    		java.util.Date date = new java.util.Date();
    		String str = simpleDateFormat.format(date);
    		Random random = new Random();
    		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
    		String pointNo = str + rannum;// 当前时间
    		
    		pointsHistory = new PointsHistory();
    		pointsHistory.setUserId(user.getId());
    		pointsHistory.setType(PointsHistory.POINT_TYPE_SIGN);
    		pointsHistory.setCurrentPoints(user.getPoints());
    		pointsHistory.setChangePoints(signPoints);
    		pointsHistory.setCreateTime(currentTime);
    		pointsHistory.setPointNo(pointNo);
    		pointsHistoryService.insert(pointsHistory);
    		
    		body.setIntegral(String.valueOf(signPoints));
    		body.setCount(String.valueOf(continuationSignDays-1));
    		body.setContinuationSignDays(continuationSignDays-1);
    		
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "获取我的活动列表接口", notes = "获取我的活动列表接口")
	@RequestMapping(value = "getMyActivityList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetMyActivityListResponse getMyActivityList(@RequestBody ApiGetMyActivityListRequest request)  {
    		ApiGetMyActivityListResponse response = new ApiGetMyActivityListResponse();
    		ApiGetMyActivityListResponseModel body = new ApiGetMyActivityListResponseModel();
    		List<ApiGetMyActivityListResponseModelList> list = new ArrayList<ApiGetMyActivityListResponseModelList>();
    		ApiGetMyActivityListResponseModelList data = null;
    		User user = null;
    		List<ActivityEnroll> activityEnrolls = null;
    		ActivityEnroll activityEnroll = null;
    		Activity activity = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		
    		user = isLogin(Long.parseLong(request.getParams().getUserid()));
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		params = new HashMap<String, Object>();
    		params.put("userId", request.getParams().getUserid());
    		activityEnrolls = activityEnrollService.find(params);
    		if(activityEnrolls != null) {
    			for(i = 0 ; i < activityEnrolls.size(); i++) {
    				activityEnroll = activityEnrolls.get(i);
    				params = new HashMap<String, Object>();
    	    			params.put("id", activityEnroll.getActivityId());
    				activity = activityService.findOne(params);
    				if(activity != null) {
    					data = new ApiGetMyActivityListResponseModelList();
    					Area area = this.getPrevAddress(activity.getRegionId());
    					if(area != null) {
    						data.setAddress(area.getAddress() + activity.getAddrDetail());
    					} else {
    						data.setAddress(activity.getAddrDetail());
    					}
		    	    		data.setEndTime(getStringDate(activity.getEndTime()));
		    	    		data.setIcon(getAbsoulteImageUrl(activity.getCoverImage()));
		    	    		data.setId(String.valueOf(activity.getId()));
		    	    		data.setPrice(String.valueOf(activity.getPrice()));
		    	    		data.setStartTime(this.getStringDate(activity.getStartTime()));
		    	    		data.setStatus(String.valueOf(getActivityStatus(activity)));
		    	    		data.setTitle(activity.getTitle());
		    	    		switch(activity.getType()) {
		    	    		case Activity.TYPE_STORE :
		    	    			data.setTypeStr("门店活动");
		    	    			break;
		    	    		case Activity.TYPE_CO_SELLER :
		    	    			data.setTypeStr("合作商家活动");
		    	    			break;
		    	    		default :
		    	    			break;
		    	    		}
		    	    		
		    	    		list.add(data);
    				}
    			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "搜索接口", notes = "搜索接口")
	@RequestMapping(value = "search", method = RequestMethod.POST)
	@ResponseBody
	public ApiSearchResponse search(@RequestBody ApiSearchRequest request)  {
    		ApiSearchResponse response=new ApiSearchResponse();
    		ApiSearchResponseModel body = new ApiSearchResponseModel();
    		List<ApiSearchResponseModelGoodList> goodList = new ArrayList<ApiSearchResponseModelGoodList>();
    		List<ApiSearchResponseModelShopList> shopList = new ArrayList<ApiSearchResponseModelShopList>();
    		ApiSearchResponseModelGoodList goods = null;
    		ApiSearchResponseModelShopList shop = null;
    		
    		goods = new ApiSearchResponseModelGoodList();
    		goods.setCount("10");
    		goods.setIcon("https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=1304450144,2103155273&fm=85&s=D511C3316146CB5B1CA8386C03009033");
    		goods.setId("1");
    		goods.setKind("kind");
    		goods.setLevel("100");
    		goods.setPrice("80");
    		goods.setTitle("商品标题1");
    		goods.setUnit("unit1");
    		goodList.add(goods);
    		goods = new ApiSearchResponseModelGoodList();
    		goods.setCount("20");
    		goods.setIcon("https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=1304450144,2103155273&fm=85&s=D511C3316146CB5B1CA8386C03009033");
    		goods.setId("2");
    		goods.setKind("kind2");
    		goods.setLevel("90");
    		goods.setPrice("100");
    		goods.setTitle("商品标题2");
    		goods.setUnit("unit2");
    		goodList.add(goods);
    		goods = new ApiSearchResponseModelGoodList();
    		goods.setCount("40");
    		goods.setIcon("https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=1304450144,2103155273&fm=85&s=D511C3316146CB5B1CA8386C03009033");
    		goods.setId("3");
    		goods.setKind("kind3");
    		goods.setLevel("98");
    		goods.setPrice("19");
    		goods.setTitle("商品标题3");
    		goods.setUnit("unit3");
    		goodList.add(goods);
    		
    		shop = new ApiSearchResponseModelShopList();
    		shop.setAddress("上海市普陀区武宁路");
    		shop.setDistance("1000");
    		shop.setIcon("https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=1304450144,2103155273&fm=85&s=D511C3316146CB5B1CA8386C03009033");
    		shop.setId("1");
    		shop.setIsSelf("1");
    		shop.setLevel("90");
    		shop.setTitle("商家名称1");
    		shopList.add(shop);
    		shop = new ApiSearchResponseModelShopList();
    		shop.setAddress("上海市普陀区武宁路");
    		shop.setDistance("3000");
    		shop.setIcon("https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=1304450144,2103155273&fm=85&s=D511C3316146CB5B1CA8386C03009033");
    		shop.setId("2");
    		shop.setIsSelf("1");
    		shop.setLevel("89");
    		shop.setTitle("商家名称2");
    		shopList.add(shop);
    		shop = new ApiSearchResponseModelShopList();
    		shop.setAddress("上海市普陀区武宁路");
    		shop.setDistance("2000");
    		shop.setIcon("https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=1304450144,2103155273&fm=85&s=D511C3316146CB5B1CA8386C03009033");
    		shop.setId("3");
    		shop.setIsSelf("0");
    		shop.setLevel("80");
    		shop.setTitle("商家名称3");
    		shopList.add(shop);
    		
    		body.setGoodList(goodList);
    		body.setShopList(shopList);
    		response.setBody(body);
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "加盟/编辑接口", notes = "加盟/编辑接口")
	@RequestMapping(value = "joinOrEdit", method = RequestMethod.POST)
	@ResponseBody
	public ApiJoinResponse joinOrEdit( @RequestBody ApiJoinRequest request)  {
    	logger.info("商家加盟:"+ JsonMapper.nonDefaultMapper().toJson(request.getParams()));
    		ApiJoinResponse response=new ApiJoinResponse();
    		Map<String, Object> params = null;
    		//得到用户信息
    		User user = isLogin(request.getParams().getUserid());
    		Shop shop = null;
    		boolean isAdd = false;
    		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
    		String[] openTimes = null;
    		String[] openStartTimes = null;
    		String[] openEndTimes = null;
    		Time startTime = null;
    		Time endTime = null;
    		
    		if(user == null) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		
    		params = new HashMap<String, Object>();
    		params.put("userId", user.getId());
    		//判断用户是否注册过商家
    		shop = shopService.findOne(params);
    		if(shop == null) {
    			isAdd = true;
    			shop = new Shop();
    			//经
    			shop.setLongitude(0.0f);
    			//纬
        		shop.setLatitude(0.0f);
        		//地区id
        		shop.setRegionId(0L);
        		//创建时间
        		shop.setCreateTime(currentTime);
        		//是否异业联盟
        		shop.setIsUnion(Shop.UNION_DIFF);
        		//是否官方店铺
        		shop.setIsOfficial(0);
    		}
    		//商家经营时间
    		openTimes = StringUtils.split(request.getParams().getTime(), "-");
    		//开始时间
    		openStartTimes = StringUtils.split(openTimes[0], ":");
    		//结束时间
    		openEndTimes = StringUtils.split(openTimes[1], ":");
    		
    		//时间格式转换
    		startTime = new Time(Integer.parseInt(openStartTimes[0]), Integer.parseInt(openStartTimes[1]),0);
    		endTime = new Time(Integer.parseInt(openEndTimes[0]),Integer.parseInt(openEndTimes[1]),0);
    		
    		shop.setUserId(user.getId());
    		shop.setName(request.getParams().getName());
    		shop.setIntroduce(request.getParams().getDetail());
    		shop.setTypeId(Long.parseLong(request.getParams().getType()));
    		shop.setPhone(request.getParams().getPhone());
    		shop.setAddress(request.getParams().getAddress());
    		shop.setUpdateTime(currentTime);
    		shop.setStatus(Shop.STATUS_WAIT_CHECK);
    		shop.setOpenStartTime(startTime);
    		shop.setOpenEndTime(endTime);
    		
    		if(isAdd) {
    			System.out.println("进来了？");
    			shopService.insert(shop);
    		} else {
    			shopService.update(shop);
    		}
    		
		return response;
	}
    
    @IgnoreAuth
	@ApiOperation(value = "商户加盟", notes = "商户加盟")
	@RequestMapping(value = "/addBusiness", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<String> addBusiness(@CurrentUserId Long userId,@RequestBody Shop shop) {
    	Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
    	ApiJoinResponse response=new ApiJoinResponse();
    	User user = isLogin(userId);
    	if(user == null) {
			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
			return new ObjectDataResponse<String>(response.toString());
		}
    	//判断用户是否注册过商家
    	Map<String, Object> params = new HashMap<String, Object>();
    	params.put("userId", userId);
    	Shop  shopDataShop = shopService.findOne(params);
    	
    	Boolean resultData=true;
    	if (shopDataShop==null) {
    		shop.setLongitude(0.0f);
    		shop.setLatitude(0.0f);
    		shop.setRegionId(0L);
    		shop.setCreateTime(currentTime);
    		//是否异业联盟 
    		shop.setIsUnion(1);
    		//是否官方店铺
    		shop.setIsOfficial(0);
    		shop.setStatus(1);
    		//添加商户
    		//营业时间转换
    		Time openStartTime =Time.valueOf(shop.getOpenTime());
    		Time openEndTime =Time.valueOf(shop.getFinishTime());
    		shop.setOpenStartTime(openStartTime);
    		shop.setOpenEndTime(openEndTime);
    		shop.setUserId(userId);
    		resultData=shopService.insert(shop);
    		//添加单张资质图片
    		ShopAptitude shopAptitude = new ShopAptitude();
    		shopAptitude.setShopId(shop.getId());
    		shopAptitude.setImage(shop.getAptitudeImage());
    		shopAptitudeService.insert(shopAptitude);
    		//添加多张商家图片
    		String[] shopImage = shop.getShopImage().split(",");
    		for (String string : shopImage) {
				ShopImage shopImage2 = new ShopImage();
				shopImage2.setShopId(shop.getId());
				shopImage2.setImage(string);
				shopImageService.insert(shopImage2);
			}
		}
    	
    	if (resultData) {
			//生成消息
			Message message = new Message();
			message.setUserId(userId);
			message.setType(1);
			message.setPushType(1);
			message.setContent("你的加盟信息已提交成功，请等待系统审核！");
			message.setCreateTime(new Timestamp(new Date().getTime()));
			message.setTitle("审核中");
			message.setRemark("审核中");
			//推送消息
			messageService.insert(message);
			//极光推送
			try {
				MsgPushUtils.addJPush(message.getContent(), userId.toString());
			} catch (APIConnectionException e) {
				e.printStackTrace();
			} catch (APIRequestException e) {
				e.printStackTrace();
			}
		}
    	
    	
    	if (resultData) {
			return new ObjectDataResponse<String>("success");
		} else {
			return new ObjectDataResponse<String>("error");
		}
	}
    
    @IgnoreAuth
	@ApiOperation(value = "商户加盟修改", notes = "商户加盟修改")
	@RequestMapping(value = "/updateBusiness", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<String> updateBusiness(@CurrentUserId Long userId,@RequestBody Shop shop){
    	Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
    	ApiJoinResponse response=new ApiJoinResponse();
    	User user = isLogin(userId);
    	if(user == null) {
			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
			return new ObjectDataResponse<String>(response.toString());
		}
    	
    	//判断用户是否注册过商家
    	Map<String, Object> params = new HashMap<String, Object>();
    	params.put("userId", userId);
    	Shop  shopDataShop = shopService.findOne(params);
    	
    	int data=0;
    	if (shopDataShop!=null) {
    		shop.setLongitude(0.0f);
    		shop.setLatitude(0.0f);
    		shop.setRegionId(0L);
    		shop.setCreateTime(currentTime);
//    		shop.setUnion(Shop.UNION_DIFF);
    		shop.setIsOfficial(0);
    		//商户信息修改
    		//营业时间转换
    		Time openStartTime =Time.valueOf(shop.getOpenTime());
    		Time openEndTime =Time.valueOf(shop.getFinishTime());
    		shop.setOpenStartTime(openStartTime);
    		shop.setOpenEndTime(openEndTime);
    		shop.setId(shopDataShop.getId());
    		data = shopService.update(shop);
    		//商户资质图片修改-单张
    		ShopAptitude shopAptitude = new ShopAptitude();
    		shopAptitude.setShopId(shopDataShop.getId());
    		shopAptitude.setImage(shop.getAptitudeImage());
    		shopAptitudeService.update(shopAptitude);
    		//商户图片修改-多张
    		params.put("shopId", shopDataShop.getId());
    		shopImageService.remove(params);
    		String[] shopImage = shop.getShopImage().split(",");
    		for (String string : shopImage) {
				ShopImage shopImage2 = new ShopImage();
				shopImage2.setShopId(shopDataShop.getId());
				shopImage2.setImage(string);
				shopImageService.insert(shopImage2);
			}
    		
		}
    	
    	if (data>0) {
			//生成消息
			Message message = new Message();
			message.setUserId(userId);
			message.setType(1);
			message.setPushType(1);
			message.setContent("你的加盟信息已提交成功，请等待系统审核！");
			message.setCreateTime(new Timestamp(new Date().getTime()));
			message.setTitle("审核中");
			message.setRemark("审核中");
			//推送消息
			messageService.insert(message);
			//极光推送
			try {
				MsgPushUtils.addJPush(message.getContent(), userId.toString());
			} catch (APIConnectionException e) {
				e.printStackTrace();
			} catch (APIRequestException e) {
				e.printStackTrace();
			}
		}
    	
    	if (data>0) {
			return new ObjectDataResponse<String>("success");
		} else {
			return new ObjectDataResponse<String>("error");
		}
	}
    
    @IgnoreAuth
    @ApiOperation(value = "获取加盟店铺详情接口", notes = "获取加盟店铺详情接口")
	@RequestMapping(value = "getMyShopDetail", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetMyShopDetailResponse getMyShopDetail(@RequestBody ApiGetMyShopDetailRequest request)  {
    		ApiGetMyShopDetailResponse response=new ApiGetMyShopDetailResponse();
    		ApiGetMyShopDetailResponseModel body = new ApiGetMyShopDetailResponseModel();
    		Shop shop = null;
    		Map<String, Object> params = null;
    		List<ShopImage> shopImages = null;
    		Long totalOrderCount = 0L;
    		Long canceledOrderCount = 0L;
    		User user = null;
    		ShopType shopType = null;
    		List<ShopAptitude> shopAptitudes = null;
    		
    		// 未验证数据的有效性
    		// 收入的积分和收入的钱怎么计算还需要合计
    		
    		if(noLogin(request.getParams().getUserid())) {
    			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg(ApiRestfulResponse.ERROR_NO_LOGIN);
    			return response;
    		}
    		params = new HashMap<String, Object>();
    		params.put("id", request.getParams().getUserid());
    		user = userService.findOne(params);
    		
    		params = new HashMap<String, Object>();
    		params.put("userId", request.getParams().getUserid());
    		shop = shopService.findOne(params);
    		
    		if(shop == null) {
    			//response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			//response.setResultMsg(ApiRestfulResponse.ERROR_NOT_OPEN_SHOP);
    			
    			response.setBody(body);
        		return response;
    		}
    		
    		params = new HashMap<String, Object>();
    		params.put("shopId", shop.getId());
    		shopImages = shopImageService.find(params);
    		
    		body.setIcon(getMultiImageUrls1(shopImages));
    		params = new HashMap<String, Object>();
    		params.put("shopId", shop.getId());
    		totalOrderCount = goodsOrderService.count(params);
    		body.setCount(String.valueOf(totalOrderCount));
    		params = new HashMap<String, Object>();
    		params.put("shopId", shop.getId());
    		/*params.put("status", GoodsOrder.STATUS_CANCELED);*/
    		canceledOrderCount = goodsOrderService.count(params);
    		if(totalOrderCount > 0)
    			body.setSuccess(String.valueOf(((float)canceledOrderCount / (float)totalOrderCount) * 100.00f));
    		else 
    			body.setSuccess("100");
    		body.setReview(String.valueOf(shop.getLevel()));
    		body.setIntegral(String.valueOf(user.getTotalPoints()));
    		body.setPrice(String.valueOf(user.getBalance()));
    		body.setName(shop.getName());
    		body.setDetail(shop.getIntroduce());
    		body.setType(String.valueOf(shop.getTypeId()));
    		params = new HashMap<String, Object>();
    		params.put("id", shop.getTypeId());
    		shopType = shopTypeService.findOne(params);
    		if(shopType != null) {
    			body.setTypeStr(shopType.getName());
    		} else {
    			body.setTypeStr("");
    		}
    		body.setPhone(shop.getPhone());
    		Area area = this.getPrevAddress(shop.getRegionId());
    		if(area != null) {
    			body.setAddress(area.getAddress() + shop.getAddress());
    		} else {
    			body.setAddress(shop.getAddress());
    		}
    		body.setTime(getStringTime(shop.getOpenStartTime())+"-" + getStringTime(shop.getOpenEndTime()));
    		body.setIsCheck(shop.getStatus()+"");
    		params = new HashMap<String, Object>();
    		params.put("shopId", shop.getId());
    		shopAptitudes = shopAptitudeService.find(params);
    		body.setAptitude(getMultiImageUrls2(shopAptitudes));
    		
    		response.setBody(body);
    		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "获取公司网点列表接口", notes = "获取公司网点列表接口")
	@RequestMapping(value = "getSelfSupportList", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetSelfSupportListResponse getSelfSupportList(@RequestBody ApiGetSelfSupportListRequest request)  {
    		ApiGetSelfSupportListResponse response=new ApiGetSelfSupportListResponse();
    		ApiGetSelfSupportListResponseModel body = new ApiGetSelfSupportListResponseModel();
    		List<ApiGetSelfSupportListResponseModelList> list = new ArrayList<ApiGetSelfSupportListResponseModelList>();
    		ApiGetSelfSupportListResponseModelList data = null;
    		Map<String, Object> params = null;
    		int i = 0;
    		List<Shop> shops = null;
    		Shop shop = null;
    		ShopImage shopImage = null;
    		
    		params = new HashMap<String, Object>();
    		params.put("union", Shop.UNION_COMPANY);
    		params.put("typeId", request.getParams().getType());
    		
    		String sortStr = request.getParams().getSort();//筛选条件，0:距离最近，1：好评优先
    		switch (Integer.valueOf(sortStr)) {
			case 0:
				//TODO 距離排序
				params.put("orderBy", "");//距離排序
				break;
			case 1:
				params.put("orderBy", "level desc");
				break;
			default:
				break;
			}
    		
    		shops = shopService.find(params);
    		
    		if(shops != null) {
    			for(i = 0 ; i < shops.size() ; i++) {
    				Area area = null;
    				shop = shops.get(i);
    				data = new ApiGetSelfSupportListResponseModelList();
    				area = getPrevAddress(shop.getRegionId());
    				if(area != null) {
    					data.setAddress(area.getAddress() + shop.getAddress());
    				} else {
    					data.setAddress(shop.getAddress());
    				}
    				
    				params = new HashMap<String, Object>();
    				params.put("shopId", shop.getId());
    				shopImage = shopImageService.findOne(params);
	    	    		if(shopImage != null) {
	    	    			data.setIcon(getAbsoulteImageUrl(shopImage.getImage()));
	    	    		} else {
	    	    			data.setIcon("");
	    	    		}
	    	    		
	    	    		data.setId(String.valueOf(shop.getId()));
	    	    		data.setTitle(shop.getName());
	    	    		data.setDistance("1000");
	    	    		data.setLevel(String.valueOf(shop.getLevel()));
	    	    		list.add(data);
    			}
    		}
    		
    		body.setList(list);
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "获取配置信息接口", notes = "获取配置信息接口")
	@RequestMapping(value = "getConfigInfo", method = RequestMethod.POST)
	@ResponseBody
	public ApiGetConfigResponse getConfigInfo(@RequestBody ApiGetConfigRequest request)  {
    		ApiGetConfigResponse response=new ApiGetConfigResponse();
    		ApiGetConfigResponseModel body = new ApiGetConfigResponseModel();
    		String field = "";
    		
    		switch(Integer.parseInt(request.getParams().getType())) {
    		case ApiGetConfigRequestModel.CONFIG_USER_PROTOCOL :
    			field = SysConfig.CONFIG_USER_PROTOCOL;
    			break;
    		case ApiGetConfigRequestModel.CONFIG_ABOUT_US :
    			field = SysConfig.CONFIG_ABOUT_US;
    			break;
    		case ApiGetConfigRequestModel.CONFIG_BALANCE_DESC :
    			field = SysConfig.CONFIG_BALANCE_DESC;
    			break;
    		case ApiGetConfigRequestModel.CONFIG_POINTS_DESC :
    			field = SysConfig.CONFIG_POINTS_DESC;
    			break;
    		default :
    			break;
    		}
    		
    		if(!field.equals("")) {
    			SysConfig sysConfig = getSysConfig(field);
    			body.setDetail(sysConfig != null ? sysConfig.getValue() : "");
    		} else {
    			body.setDetail("");
    		}
    		
    		response.setBody(body);
    		
		return response;
	}
    
    @IgnoreAuth
    @ApiOperation(value = "订单列表接口", notes = "获取订单列表接口")
    @RequestMapping(value = "getOrderList", method = RequestMethod.POST)
    @ResponseBody
    public ApiGetGoodsOrderListResponse getOrderList(@RequestBody ApiGetGoodsOrderListRequest request)  {
    	ApiGetGoodsOrderListResponse response=new ApiGetGoodsOrderListResponse();
    	ApiGetGoodsOrderListResponseModel body = new ApiGetGoodsOrderListResponseModel();
    	List<ApiGetGoodsOrderListResponseModelList> list = new ArrayList<ApiGetGoodsOrderListResponseModelList>();
    	ApiGetGoodsOrderListResponseModelList data = null;
    	ApiGetGoodsOrderListResponseGoodsList goodsListData = null;
    	List<ApiGetGoodsOrderListResponseGoodsList> goodsDataList = null;
    	
    	String userIdStr = request.getParams().getUserid();
    	long userId = Long.parseLong(userIdStr);
    	
    	//0：全部，1：待发货，2：待收货，3：已结束
    	String type = request.getParams().getType();
    	int typeInt = Integer.valueOf(type);
    	GoodsOrder goodsOrder = new GoodsOrder();
    	goodsOrder.setUserId(userId);
    	goodsOrder.setPageSize(Integer.valueOf(request.getParams().getNum()));
    	goodsOrder.setPageIndex(Integer.valueOf(request.getParams().getPage()));
    	
    	switch (typeInt) {
    	//订单状态。 1: 待支付 2: 已支付待发货 3: 已支付待收货 4: 已支付已收货（完成） 5: 订单已取消
		case 1://待发货
			goodsOrder.setStatus(2);
			break;
		case 2://待收货
			goodsOrder.setStatus(3);
			break;
		case 3://已结束
			goodsOrder.setStatus(4);
			break;
		default://全部
			break;
		}
    	List<GoodsOrder> goodsOrderResult = goodsOrderService.find(goodsOrder);
    	for (GoodsOrder gOrder : goodsOrderResult) {
    		data = new ApiGetGoodsOrderListResponseModelList();
    		data.setId(gOrder.getId()+"");
    		data.setStatus(gOrder.getStatus()+"");
    		switch (gOrder.getStatus()) {//订单状态。 1: 待支付 2: 已支付待发货 3: 已支付待收货 4: 已支付已收货（完成） 5: 订单已取消
			case 1:
				data.setStatusStr("待支付");
				break;
			case 2:
				data.setStatusStr("已支付待发货 ");
				break;
			case 3:
				data.setStatusStr("已支付待收货");
				break;
			case 4:
				data.setStatusStr("已支付已收货（完成）");
				break;
			case 5:
				data.setStatusStr("订单已取消");
				break;
			default:
				break;
			}
    		data.setTime(gOrder.getCreateTime()+"");

			//商城专区名称
			Goods goods = new Goods();
			Map<String, Object> params = new HashMap<String, Object>();
			/*params.put("id", gOrder.getGoodsId());*/
			goods = goodsService.findOne(params);
			switch (goods.getType()) {//商品种类 1：鸿豆商品 2：积分商品 3：旅游商品 4：返利商品'
			case 1:
				data.setType("鸿豆商品");
				break;
			case 2:
				data.setType("积分商品");
				break;
			case 3:
				data.setType("旅游商品");
				break;
			case 4:
				data.setType("返利商品");
				break;
			default:
				break;
			}
			goodsListData = new ApiGetGoodsOrderListResponseGoodsList();
			goodsDataList = new ArrayList<ApiGetGoodsOrderListResponseGoodsList>();
			goodsListData.setId(goods.getId()+"");
			GoodsImage goodsImage = null;
			params = new HashMap<String, Object>();
			/*params.put("id", gOrder.getGoodsId());*/
			goodsImage = goodsImageService.findOne(params);
			if (goodsImage != null) {
				goodsListData.setIcon(goodsImage.getImage());
			}
			goodsListData.setTitle(goods.getName());
			params = new HashMap<String, Object>();
			params.put("orderId", gOrder.getId());
			GoodsOrderFeature goodsOrderFeature = goodsOrderFeatureService.findOne(params);
			if (goodsOrderFeature != null) {
				goodsListData.setPrice(goodsOrderFeature.getPrice()+"");//商品单价
			}
			switch (goods.getType()) {//商品种类 1：鸿豆商品 2：积分商品 3：旅游商品 4：返利商品'
			case 1:
				goodsListData.setKind("1");
				break;
			case 2:
				goodsListData.setKind("2");
				break;
			case 3:
				goodsListData.setKind("3");
				break;
			case 4:
				goodsListData.setKind("4");
				break;
			default:
				break;
			}
			/*goodsListData.setCount(gOrder.getCount()+"");*/
			//规格数组，数组每项：规格id|规格值id,例：[1|2，2|1]
			String goodsOrderFeatureValueStr = "";
			String[] goodsOrderFeatureValue = null;
			params = new HashMap<String, Object>();
			params.put("orderId", gOrder.getId());
			GoodsOrderFeature goodsOrderFeatureResult = goodsOrderFeatureService.findOne(params);
			if (goodsOrderFeatureResult != null) {
				String featureValueIdStr = goodsOrderFeatureResult.getValue();
				String[] featureValueIds = featureValueIdStr.split(",");
				goodsOrderFeatureValue = new String[featureValueIds.length];
				for (int i=0; i<featureValueIds.length; i++) {
					params = new HashMap<String, Object>();
					params.put("id", Long.parseLong(featureValueIds[i])); 
					GoodsCategoryFeatureValue goodsCategoryFeatureValue = goodsCategoryFeatureValueService.findOne(params);
					String valueName = goodsCategoryFeatureValue.getName();
					if (i == 0) {
						goodsOrderFeatureValueStr += valueName;
					}else {
						goodsOrderFeatureValueStr += ","+valueName;
					}
					goodsOrderFeatureValue[i] = featureValueIds[i];
				}
			}
			
			goodsListData.setFeatureStr(goodsOrderFeatureValueStr);
			goodsListData.setFeature(goodsOrderFeatureValue);
			//total
			float price = goodsOrderFeatureResult.getPrice();
			int count = 0;
			float total = price * count;
			data.setTotal(total+"");//total
			goodsDataList.add(goodsListData);
			data.setGoodsList(goodsDataList);
			data.setOrderNO(gOrder.getOrderNo());
			list.add(data);
		}
    	body.setList(list);
    	response.setBody(body);
    	return response;
    }
    
    @IgnoreAuth
    @ApiOperation(value = "订单详情", notes = "获取订单详情接口")
    @RequestMapping(value = "getOrderDetail", method = RequestMethod.POST)
    @ResponseBody
    public ApiGetGoodsOrderDetailResponse getOrderDetail(@RequestBody ApiGetGoodsOrderDetailRequest request)  {
    	ApiGetGoodsOrderDetailResponse response=new ApiGetGoodsOrderDetailResponse();
    	ApiGetGoodsOrderDetailResponseModel body = new ApiGetGoodsOrderDetailResponseModel();
    	ApiGetGoodsOrderDetailResponseModelUserInfo userInfo = new ApiGetGoodsOrderDetailResponseModelUserInfo();
    	ApiGetGoodsOrderDetailResponseModelShopInfo shopInfo = new ApiGetGoodsOrderDetailResponseModelShopInfo();
    	List<ApiGetGoodsOrderDetailResponseModelGoodsList> goodsDataList = new ArrayList<ApiGetGoodsOrderDetailResponseModelGoodsList>();
    	ApiGetGoodsOrderDetailResponseModelGoodsList goodsList = null;
    	
    	String userId = request.getParams().getUserid();//用户id
    	String id = request.getParams().getId();//订单id
    	
    	GoodsOrder goodsOrder = new GoodsOrder();
    	goodsOrder.setUserId(Long.parseLong(userId));
    	goodsOrder.setId(Long.parseLong(id));
    	GoodsOrder goodsOrderResult = goodsOrderService.findOne(goodsOrder);
    	body.setOrderNO(goodsOrderResult.getOrderNo());
    	body.setStatus(goodsOrderResult.getStatus()+"");
    	body.setTime(goodsOrderResult.getCreateTime()+"");
    	body.setDelivery(goodsOrderResult.getTakeGoodsType()+"");
    	switch (goodsOrderResult.getTakeGoodsType()) {//配送方式，1:到店自提，2：门店配送，3：快递配送
		case 1:
			body.setDeliveryStr("到店自提");
			break;
		case 2:
			body.setDeliveryStr("门店配送");
			break;
		case 3:
			body.setDeliveryStr("快递配送");
			break;
		default:
			break;
		}
    	body.setRemark(goodsOrderResult.getMemo());
    	//userInfo
    	userInfo.setName("");
    	userInfo.setPhone("");
    	/*userInfo.setAddress(getAddress(goodsOrderResult.getRegionId())+goodsOrderResult.getAddress());*/
    	body.setUserInfo(userInfo);
    	//goodsList
    	Goods goods = new Goods();
    	Map<String, Object> params = new HashMap<String, Object>();
    	/*params.put("id", goodsOrderResult.getGoodsId());*/
    	goods = goodsService.findOne(params);
    	if (goods == null) {
    		response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    		response.setResultMsg("商品不能为空！");
			return response;
		}
    	goodsList = new ApiGetGoodsOrderDetailResponseModelGoodsList();
    	goodsList.setId(goods.getId()+"");
    	
		GoodsImage goodsImage = new GoodsImage();
    	params = new HashMap<String, Object>();
    	params.put("goodsId", goods.getId());
    	goodsImage = goodsImageService.findOne(params);
		if (goodsImage != null) {
			goodsList.setIcon(goodsImage.getImage());
		}
		goodsList.setTitle(goods.getName());
		//商品价格
		float total = 0.0f;
		params = new HashMap<String, Object>();
		params.put("orderId", goodsOrderResult.getId());
		GoodsOrderFeature goodsOrderFeature = goodsOrderFeatureService.findOne(params);
		if (goodsOrderFeature != null) {
			float price = goodsOrderFeature.getPrice();
			int count = 0;
			total = price * count ;
			goodsList.setPrice(price+"");
		}
		body.setTotal(total+"");
		switch (goods.getType()) {//商品种类 1：鸿豆商品 2：积分商品 3：旅游商品 4：返利商品'
		case 1:
			goodsList.setKind("1");
			break;
		case 2:
			goodsList.setKind("2");
			break;
		case 3:
			goodsList.setKind("3");
			break;
		case 4:
			goodsList.setKind("4");
			break;
		default:
			break;
		}
		/*goodsList.setCount(goodsOrderResult.getCount()+"");*/
		goodsDataList.add(goodsList);
		body.setGoodsList(goodsDataList);
    	//shopInfo
		Shop shop = new Shop();
    	params = new HashMap<String, Object>();
    	params.put("id", goodsOrderResult.getShopId());
    	shop = shopService.findOne(params);
    	if (shop != null) {
    		shopInfo.setId(shop.getId()+"");
    		shopInfo.setLevel(shop.getLevel()+"");
    		shopInfo.setTitle(shop.getName());
    		shopInfo.setAddress(getAddress(shop.getRegionId()));
    		ShopImage shopImage = new ShopImage();
    		shopImage.setId(shop.getId());
    		shopImage = shopImageService.findOne(shopImage);
    		shopInfo.setIcon(shopImage.getImage());
    		shopInfo.setIsSelf(shop.getIsOfficial() == 0 ? "否" : "是");//是否官方店铺 0：否 1：是
    		shopInfo.setDistance("100厘米");
    		body.setShopInfo(shopInfo);
		}
    	response.setBody(body);
    	return response;
    }
    
    @IgnoreAuth
    @ApiOperation(value = "订单操作", notes = "订单操作接口")
    @RequestMapping(value = "orderHandle", method = RequestMethod.POST)
    @ResponseBody
    public ApiGetGoodsOrderOperationResponse orderHandle(@RequestBody ApiGetGoodsOrderOperationRequest request)  {
    	ApiGetGoodsOrderOperationResponse response=new ApiGetGoodsOrderOperationResponse();
    	
    	String userId = request.getParams().getUserid();
    	String orderId = request.getParams().getId();//订单id
    	String type = request.getParams().getType();//1:催单，2：确认收货 3再来一单
    	int typeInt = Integer.valueOf(type);
    	
    	if (typeInt == 1) {//1:催单
    		String content = String.format("您的验证码是：【%s】请不要把验证码泄露给其他人。", "催单");
			User user = new User();
			user.setId(Long.parseLong(userId));
			user = userService.findOne(user);
			String phoneNumber = user.getPhone();
			boolean success = sendSMS(content, phoneNumber);
			if (success) {
				response.setResult(String.valueOf(0));
    			response.setResultMsg("催单收获成功！");
			}else {
				response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg("催单收获失败！");
			}
		}
    	if (typeInt == 2) {//2：确认收货
    		GoodsOrder goodsOrder = new GoodsOrder();
    		goodsOrder.setUserId(Long.parseLong(userId));
    		goodsOrder.setId(Long.parseLong(orderId));
    		goodsOrder.setStatus(4);
    		int line = goodsOrderService.update(goodsOrder);
    		if (line > 0) {
    			response.setResult(String.valueOf(0));
    			response.setResultMsg("确认收获成功！");
			}else {
				response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
    			response.setResultMsg("确认收获失败！");
			}
		}
    	if (typeInt == 3) {//3：再来一单 判断商品是否下架  判断商品库存是否大于购买数量
    		Map<String, Object> params = new HashMap<String, Object>();
    		params.put("orderId", Long.parseLong(orderId));
    		GoodsOrder goodsOrder = goodsOrderService.findOne(params);
    		if (goodsOrder == null) {
        		response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
        		response.setResultMsg("订单不存在！");
    			return response;
			}
    		long goodsId = 0L;
    		params = new HashMap<String, Object>();
    		params.put("id", goodsId);
    		Goods goods = goodsService.findOne(params);
    		if (goods == null) {
        		response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
        		response.setResultMsg("商品不存在！");
    			return response;
			}
    		if (goods.getStatus() == 3) {// 3 已下架
        		response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
        		response.setResultMsg("商品已下架！");
    			return response;
			}
    		int inventory = goods.getInventory();//商品总库存
    		int count = 0;//购买数量
    		if (inventory < count) {
        		response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
        		response.setResultMsg("购买的数量不能大于商品库存数量！");
    			return response;
			}
		}
    	return response;
    }
    
    @IgnoreAuth
    @ApiOperation(value = "商品下单", notes = "商品下单接口")
    @RequestMapping(value = "goodsOrder", method = RequestMethod.POST)
    @ResponseBody
	public ApiGetGoodsOrderResponse goodsOrder(@RequestBody ApiGetGoodsOrderRequest request) {
		ApiGetGoodsOrderResponse response = new ApiGetGoodsOrderResponse();
		GoodsOrder goodsOrder = new GoodsOrder();
		goodsOrder.setUserId(Long.parseLong(request.getParams().getUserid()));//用户id
		/*goodsOrder.setGoodsId(Long.parseLong(request.getParams().getId()));//商品Id
*/		goodsOrder.setTakeGoodsType(Integer.valueOf(request.getParams().getType()));// 提货方式。 1: 到店自提 2：门店配送 3：快递配送
		if (Integer.valueOf(request.getParams().getType()) == 3) {// 门店id号。 对take_goods_type＝3有效
			if (Integer.valueOf(request.getParams().getOtherID()) == 1) {// 其他id，delivery=1表示门店id；delivery=2,3时，表示收货地址id
				/*goodsOrder.setTakeShopId(Long.valueOf(request.getParams().getOtherID()));*/
			}
		} else {// 1: 到店自提 2：门店配送 对于take_goods_type＝1，2有效
			UserAddress userAddress = new UserAddress();
			userAddress.setId(Long.parseLong(request.getParams().getOtherID()));
			userAddress = userAddressService.findOne(userAddress);
			/*goodsOrder.setName(userAddress.getName());
			goodsOrder.setPhone(userAddress.getPhone());
			goodsOrder.setAddress(userAddress.getAddress());
			goodsOrder.setRegionId(userAddress.getRegionId());*/
		}
		goodsOrder.setMemo(request.getParams().getRemark());// 备注
		goodsOrder.setAmount(Float.parseFloat(request.getParams().getPrice()));// 应付金额
		/*goodsOrder.setCount(Integer.valueOf(request.getParams().getCount()));*/
		goodsOrder.setCreateTime(new Timestamp(System.currentTimeMillis()));

		goodsOrder.setStatus(1);// status 订单状态
		// 订单编号
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
		java.util.Date date = new java.util.Date();
		String str = simpleDateFormat.format(date);
		Random random = new Random();
		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
		String orderNo = str + rannum;// 当前时间
		goodsOrder.setOrderNo(orderNo);
		
		logger.debug("订单编号：=========> " + orderNo);
		if (!goodsOrderService.insert(goodsOrder)) {
			response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
			response.setResultMsg("创建订单失败！");
			return response;
		}
		// String type = request.getParams().getType();//类型，1：商品，2：旅游
		String payWay = request.getParams().getPayWay();// 支付方式，1:余额，2：积分
		if (Integer.valueOf(payWay) == 1) {// 余额
			User user = new User();
			user.setId(Long.parseLong(request.getParams().getUserid()));
			user = userService.findOne(user);
			if (user == null) {
				response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
				response.setResultMsg("无此用户！");
				return response;
			}
			User updateUser = new User();
			float remainAmount = user.getBalance();
			float goodsPrice = Float.parseFloat(request.getParams().getPrice());
			float flag = remainAmount - goodsPrice;
			if (flag >= 0) {
				updateUser.setId(user.getId());
				updateUser.setBalance(flag);
				userService.update(updateUser);
				response.setResultMsg("交易成功！");
				
				BalanceHistory balanceHistory = new BalanceHistory();
				balanceHistory.setUserId(Long.parseLong(request.getParams().getUserid()));
				balanceHistory.setType(6);//6系统扣除：后台系统给用户减少
				//当前余额
				User userFind = new User();
				userFind.setId(Long.parseLong(request.getParams().getUserid()));
				userFind = userService.findOne(userFind);
				/*balanceHistory.setCurrentAmount(userFind.getBalance());//当前余额
				
				balanceHistory.setChangeAmount(goodsPrice);//变动金额
*/				balanceHistory.setOrderNo(orderNo);//订单编号
				balanceHistory.setCreateTime(new Timestamp(System.currentTimeMillis()));
				balanceHistoryService.insert(balanceHistory);
			} else {
				response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
				response.setResultMsg("余额不足！");
				return response;
			}

		} else if (Integer.valueOf(payWay) == 2) {// 积分
			User user = new User();
			user.setId(Long.parseLong(request.getParams().getUserid()));
			user = userService.findOne(user);
			if (user == null) {
				response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
				response.setResultMsg("无此用户！");
				return response;
			}
			User updateUser = new User();
			int remainAmount = user.getPoints();
			int goodsPrice = Integer.valueOf(request.getParams().getPrice());
			int flag = remainAmount - goodsPrice;
			if (flag >= 0) {
				updateUser.setId(user.getId());
				updateUser.setPoints(flag);
				userService.update(updateUser);
				response.setResultMsg("交易成功！");
				
				PointsHistory pointsHistory = new PointsHistory();
				pointsHistory.setUserId(goodsOrder.getUserId());
				pointsHistory.setType(6);//6 系统扣除：后台系统给用户减少
				//当前积分
				User userFind = new User();
				userFind.setId(Long.parseLong(request.getParams().getUserid()));
				userFind = userService.findOne(userFind);
				
				// 流水编号
				SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMddhhmmss");
				java.util.Date date1 = new java.util.Date();
				String str1 = simpleDateFormat1.format(date1);
				Random random1 = new Random();
				int rannum1 = (int) (random1.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
				String pointNo = str1 + rannum1;// 当前时间
				
				pointsHistory.setCurrentPoints(userFind.getPoints());//当前积分
				pointsHistory.setChangePoints(goodsPrice);//变动的积分
				pointsHistory.setCreateTime(new Timestamp(System.currentTimeMillis()));
				pointsHistory.setPointNo(pointNo);
				pointsHistoryService.insert(pointsHistory);
				
			} else {
				response.setResult(ApiRestfulResponse.DEFAULT_ERROR);
				response.setResultMsg("积分余额不足！");
				return response;
			}
		}

		GoodsOrderFeature goodsOrderFeature = new GoodsOrderFeature();
		goodsOrderFeature.setOrderId(goodsOrder.getId());
		String[] values = request.getParams().getFeature();
		String value = "";
		for (int i=0; i< values.length; i++) {
			if (i == 0) {
				value += values[i];
			}else{
				value += ","+values[i];
			}
		}
		goodsOrderFeature.setValue(value);
		if (Integer.valueOf(request.getParams().getPayWay()) == 1) {
			goodsOrderFeature.setType(0);//0 现金 1 积分
		}
		if (Integer.valueOf(request.getParams().getPayWay()) == 2) {
			goodsOrderFeature.setType(1);//0 现金 1 积分
		}
		goodsOrderFeature.setPrice(Float.parseFloat(request.getParams().getPrice()));//商品单价
		goodsOrderFeatureService.insert(goodsOrderFeature);
		//下单成功 修改状态为 已支付代发货
		GoodsOrder goodsOrderUpdate = new GoodsOrder();
		goodsOrderUpdate.setId(goodsOrder.getId());
		goodsOrderUpdate.setStatus(2);//已支付待发货
		goodsOrderService.update(goodsOrderUpdate);
		
		return response;
	}
    
    /**
     * 发送短信
     * @param content 短信内容
     * @param phoneNumber
     * @return true 成功  false 失败
     */
    private boolean sendSMS(String content, String phoneNumber){
		HttpClientUtil  httpClientUtil = new HttpClientUtil();  
        Map<String,String> createMap = new HashMap<String,String>();  
        createMap.put("account",MESSAGE_APIID);  //APIID
        createMap.put("password",MESSAGE_PASSWORD);  
        createMap.put("mobile",phoneNumber); 
        createMap.put("content",content);  
        long epoch = System.currentTimeMillis()/1000;
        createMap.put("time",String.valueOf(epoch));  
        createMap.put("format","xml");//设置返回值类型  
        
        String result = httpClientUtil.doPost(MESSAGE_URL, createMap, "utf-8");
		System.out.println("------------------>>>>>>>>>" + result);
		int len1 = result.indexOf("</code>");
		int len2 = result.indexOf("<code>");
		String resultCode = result.substring((len2+6), len1);//返回值
		
	    //获取返回信息
		int len3 = result.indexOf("</msg>");
		int len4 = result.indexOf("<msg>");
		String msg = result.substring((len4 + 5), len3);
		if (!(resultCode != null && !resultCode.equals("") && resultCode.trim().equals("2"))) {//不成功
			System.out.println("失败原因： "+msg);
			return false;
		}
		return true;
    }
    
    /**
     * @param regionId
     * @return 省+市+区 字符串
     */
    private String getAddress(Long regionId) {
    	Region region = new Region();
    	region.setId(regionId);
    	region = regionService.findOne(region);
    	String regionName = region.getName();
    	City city = new City();
    	city.setId(region.getCityId());
    	city = cityService.findOne(city);
    	String cityName = city.getName();
    	Province province = new Province();
    	province.setId(city.getProvinceId());
    	province = provinceService.findOne(province);
    	String provinceName = province.getName();
		return provinceName+cityName+regionName;
    }
    
    private User register(String phone, String password, String nickName, String sex, String inviteCode, String avatar, boolean isThirdParty,String qrCode) throws WriterException, IOException {
    		User user = null;
    		Map<String, Object> params = null;
    		User inviteUser = null;
    		boolean haveInvite = false;
    		SysConfig sysConfig = null;
    		int givePoint = 20; //初始积分
    		PointsHistory pointsHistory = null;
    		InviteHistory inviteHistory = null;
    		UserConfig userConfig = null;
        Timestamp currentDateTime = new Timestamp((new java.util.Date()).getTime());
        
        // 手机号注册未进行头像存储
        
    		// 填充用户数据
 		user = new User();
     	user.setPhone(phone);
     	user.setPassword(EncodeUtil.encodeMD5(password));
     	user.setNickname(nickName);
     	if(isThirdParty) {
     		user.setPortrait(avatar);
     	}
     	if(sex.equals("0")) {
     		user.setSex(User.SEX_MALE);
     	} else {
     		user.setSex(User.SEX_FEMALE);
     	}
     	if(inviteCode != null && 
     	   !inviteCode.equals("")) {
     		params = new HashMap<String, Object>();
     		params.put("inviteCode", inviteCode);
     		inviteUser = userService.findOne(params);
     		if(inviteUser != null) {
     			user.setInviterUserId(inviteUser.getId());
     			haveInvite = true;
     		}
     	}
     	sysConfig = getSysConfig(SysConfig.CONFIG_REGISTER_GIVE_POINTS);
     	if(sysConfig != null) {
     		givePoint = Integer.parseInt(sysConfig.getValue());
     	}
     	user.setPoints(givePoint);
     	user.setCreateTime(currentDateTime);
     	//默认等级注入
     	UserLevel userLevel = new UserLevel();
     	userLevel.setIsDefault(0);
     	List<UserLevel> userlevelList= userLevelService.find(userLevel);
     	user.setType(userlevelList.get(0).getId().intValue());
     	
     	if(userService.insert(user)) {
     		params = new HashMap<String, Object>();
     		params.put("phone", phone);
     		user = userService.findOne(params);
     		
     		// 更新自身的邀请代码
     		user.setInviteCode(String.valueOf(user.getId()));
     		userService.update(user);
     		// 添加用户积分记录
     		
     		// 订单编号
    		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    		java.util.Date date = new java.util.Date();
    		String str = simpleDateFormat.format(date);
    		Random random = new Random();
    		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
    		String pointNo = str + rannum;// 当前时间
     		
     		pointsHistory = new PointsHistory();
         	pointsHistory.setChangePoints(givePoint);
         	pointsHistory.setCurrentPoints(givePoint);
         	pointsHistory.setCreateTime(currentDateTime);
         	pointsHistory.setType(PointsHistory.POINT_TYPE_REGISTER);
         	pointsHistory.setUserId(user.getId());
         	pointsHistory.setPointNo(pointNo);
         	pointsHistoryService.insert(pointsHistory);
         	// 添加邀请记录
         	if(haveInvite) {
         		inviteHistory = new InviteHistory();
         		inviteHistory.setUserId(inviteUser.getId());
         		inviteHistory.setInviteUserId(user.getId());
         		inviteHistory.setInviteTime(currentDateTime);
         		inviteHistory.setIsLogin(0);
         		inviteHistoryService.insert(inviteHistory);
         	}
         	// 添加用户配置
         	userConfig = new UserConfig();
         	userConfig.setUserId(user.getId());
         	userConfig.setEnableAlarm(1);
         	userConfig.setEnableSysMessageNotice(1);
         	userConfig.setEnableVoice(1);
         	userConfigService.insert(userConfig);
         	
			if(!StringUtils.isEmpty(qrCode)){
			         			
			    user.setQrcode(qrCode);
		        user.setInviterUserId(new Long(qrCode));
				userService.update(user);
			}
			             	
		    //获取本机地址
			sysConfig = getSysConfig(SysConfig.CONFIG_SHARE_BASE_URL);
			            	
     	} else {
     		return null;
     	}
    		
    	return user;
    }
    
    private User isLogin(String phone) {
    		User user = null;
    		Map<String, Object> params = null;
    		UserLoginHistory userLoginHistory = null;
    		
    		params = new HashMap<String, Object>();
    		params.put("phone", phone);
    		user = userService.findOne(params);
    		if(user == null)
    			return null;
    		
    		params = new HashMap<String, Object>();
    		params.put("userId", user.getId());
    		params.put("status", UserLoginHistory.LOGIN_STATUS_NO_LOGOUT);
    		userLoginHistory = userLoginHistoryService.findOne(params);
    		if(userLoginHistory == null)
    			return null;
    		
    		return user;
    }
    
    private User isLogin(Long id) {
		User user = null;
		Map<String, Object> params = null;
		UserLoginHistory userLoginHistory = null;
		
		params = new HashMap<String, Object>();
		params.put("id", id);
		user = userService.findOne(params);
		if(user == null)
			return null;
		
		params = new HashMap<String, Object>();
		params.put("userId", user.getId());
		params.put("status", UserLoginHistory.LOGIN_STATUS_NO_LOGOUT);
		userLoginHistory = userLoginHistoryService.findOne(params);
		if(userLoginHistory == null)
			return null;
		
		return user;
}
    
    private SysConfig getSysConfig(String field) {
    		SysConfig sysConfig = null;
    		Map<String, Object> params = new HashMap<String, Object>();
    		params = new HashMap<String, Object>();
     	params.put("field", field);
     	sysConfig = sysConfigService.findOne(params);
    		return sysConfig;
    }
    
    private User getUser(Long userId) {
    		Map<String, Object> params = new HashMap<String, Object>();
		params = new HashMap<String, Object>();
		params.put("id", userId);
		return userService.findOne(params);
    }
    
    private User getUser(String phone) {
		Map<String, Object> params = new HashMap<String, Object>();
		params = new HashMap<String, Object>();
		params.put("phone", phone);
		return userService.findOne(params);
    }
    
    private String getNickName(User user) {
    		if(user == null) {
    			return "";
    		}
    		if((user.getNickname() != null && !user.getNickname().equals(""))) {
    			return user.getNickname();
    		}
    		return user.getPhone();
    }
    
    private String getAbsoulteImageUrl(String imageUrl) {
    		SysConfig sysConfig = getSysConfig(SysConfig.CONFIG_IMAGE_BASE_URL);
    		String imageBaseUrl = (sysConfig != null) ? sysConfig.getValue() : "http://127.0.0.1";
    	
    		if(imageUrl != null && !imageUrl.equals("")) {
			if(imageUrl.contains("http://") || imageUrl.contains("https://")) {
				return imageUrl;
			} else {
				return imageBaseUrl + "/" + imageUrl;
			}
		} else {
			return "";
		}
    }
    
    private Area getPrevAddress(Long regionId) {
    		Map<String, Object> params = null;
    		Region region = null;
    		City city = null;
    		Province province = null;
    		String regionStr = "";
    		String cityStr = "";
    		String provinceStr = "";
    		Area area = new Area();
    		
		if (regionId != null && regionId > 0L) {
			params = new HashMap<String, Object>();
			params.put("id", regionId);
			area.setRegionId(regionId);
			region = regionService.findOne(params);
			if (region != null) {
				regionStr = region.getName();
				params = new HashMap<String, Object>();
				params.put("id", region.getCityId());
				area.setCityId(region.getCityId());
				city = cityService.findOne(params);
				if (city != null) {
					cityStr = city.getName();
					params = new HashMap<String, Object>();
					params.put("id", city.getProvinceId());
					area.setProvinceId(city.getProvinceId());
					province = provinceService.findOne(params);
					if (province != null) {
						provinceStr = province.getName();
					}
				}
			}
			area.setAddress(provinceStr + cityStr + regionStr);
			return area;
		} else {
			return null;
		}
    }
    
    @SuppressWarnings("deprecation")
	private String getStringDateTime(Timestamp time) {
    		if(time == null) {
			return "";
		}
    		return String.format("%04d-%02d-%02d %02d:%02d:%02d", 
			    				time.getYear() + 1900,
			    				time.getMonth() + 1,
    							time.getDate(),
    							time.getHours(),
    							time.getMinutes(),
    							time.getSeconds());
    }
    
    @SuppressWarnings("deprecation")
	private String getStringDate(Timestamp time) {
    		if(time == null) {
    			return "";
    		}
		return String.format("%04d-%02d-%02d", 
				time.getYear() + 1900,
				time.getMonth() + 1,
				time.getDate());
    }
    
    @SuppressWarnings("deprecation")
	private String getStringDate(Date time) {
    		if(time == null) {
			return "";
		}
		return String.format("%04d-%02d-%02d", 
							time.getYear(),
							time.getMonth(),
							time.getDay());
    }
    
    @SuppressWarnings("deprecation")
	private String getStringTime(Time time) {
    		if(time == null) {
			return "";
		}
		return String.format("%02d:%02d:%02d", 
							time.getHours(),
							time.getMinutes(),
							time.getSeconds());
    }
    
//    private String getNewsTags(List<NewsTag> newsTags) {
//    		String tagsStr = "";
//    		int i = 0;
//    		NewsTag tag = null;
//    		
//    		if(newsTags != null) {
//    			for(i = 0 ; i < newsTags.size(); i++) {
//    				tag = newsTags.get(i);
//    				if(i != 0) {
//    					tagsStr += ",";
//    				}
//    				tagsStr += tag.getName();
//    			}
//    		}
//    		
//    		return tagsStr;
//    }
    
    private String getMultiImageUrls1(List<ShopImage> images) {
    		String urls = "";
    		int i = 0;
    		
    		if(images != null) {
    			for(i = 0 ; i < images.size() ; i++) {
    				if(i != 0) {
    					urls += "|";
    				}
    				urls += this.getAbsoulteImageUrl(images.get(i).getImage());
    			}
    		}
    		
    		return urls;
    }
    
    private String getMultiImageUrls2(List<ShopAptitude> images) {
		String urls = "";
		int i = 0;
		
		if(images != null) {
			for(i = 0 ; i < images.size() ; i++) {
				if(i != 0) {
					urls += "|";
				}
				urls += this.getAbsoulteImageUrl(images.get(i).getImage());
			}
		}
		
		return urls;
    }
    
    private String getMultiImageUrls3(List<GoodsImage> images) {
		String urls = "";
		int i = 0;
		
		if(images != null) {
			for(i = 0 ; i < images.size() ; i++) {
				if(i != 0) {
					urls += "|";
				}
				urls += this.getAbsoulteImageUrl(images.get(i).getImage());
			}
		}
		
		return urls;
    }
    
    private int getGoodsOrderCount(Long goodsId) {
    		int count = 0;
    		
    		if(goodsId <= 0)
    			return 0;
    		
    		
    		
    		return count;
    }
    
    private boolean noLogin(String userId) {
    		return userId == null || userId.equals("") || userId.equals("0");
    }
    
    private int getActivityStatus(Activity activity) {
    		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
    		
    		if(currentTime.getTime() < activity.getStartTime().getTime()) {
    			return Activity.STATUS_NO_START;
    		} else if(currentTime.getTime() > activity.getEndTime().getTime()) {
    			return Activity.STATUS_ENDED;
    		} else {
    			return Activity.STATUS_BEING;
    		}
    }
    
    private String getActivityTypeStr(int type) {
    		switch(type) {
    		case Activity.TYPE_STORE : 
    			return "门店活动";
    		case Activity.TYPE_CO_SELLER :
    			return "合作商家活动";
    		default :
    			return "未知";
    		}
    }
    
    private int getLimitStart(int page, int num) {
    		return (page - 1) * num;
    }
    
    private int getLimitEnd(int page, int num) {
    		return num;
    }
    
    private void updateActivityStatus() {
    		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
    		Map<String, Object> params = null;
    		
		params = new HashMap<String, Object>();
		params.put("currentTime", currentTime);
		params.put("status1", "");
		params.put("status", 1);
		activityService.updateByTime(params);
		params = new HashMap<String, Object>();
		params.put("currentTime", currentTime);
		params.put("status2", "");
		params.put("status", 2);
		activityService.updateByTime(params);
		params = new HashMap<String, Object>();
		params.put("currentTime", currentTime);
		params.put("status3", "");
		params.put("status", 3);
		activityService.updateByTime(params);
    }
    
    private Float getGoodsPrice(Goods goods) {
    		Float price = 0.0f;
    		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
    		
    		if(goods.getIsSpecialPrice() == 1) {
    			if(currentTime.getTime() >= goods.getSpecialStartTime().getTime() && 
    			   currentTime.getTime() <= goods.getSpecialEndTime().getTime()) {
    				return goods.getSpecialPrice();
    			} else {
    				return goods.getPrice();
    			}
    			
    		} else {
    			return goods.getPrice();
    		}
    }
    
    private boolean isSpecialPriceGoods(Goods goods) {
    		Timestamp currentTime = new Timestamp((new java.util.Date()).getTime());
    		return (goods.getIsSpecialPrice() == 1) && 
    				currentTime.getTime() >= goods.getSpecialStartTime().getTime() && 
     			currentTime.getTime() <= goods.getSpecialEndTime().getTime();
    }
    
    
	public static String getNumber(int num){
		if (num==1) {
			return "一";
		}
		if (num==2) {
			return "二";
		}
		if (num==3) {
			return "三";
		}
		if (num==4) {
			return "四";
		}
		if (num==5) {
			return "五";
		}
		
		return null;
	}
}
